<?php
include("db/cn.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

//session_start(); // Ensure session is started



// Start session and initialize variables
if (isset($_SESSION['user_name'], $_SESSION['user_role'], $_SESSION['outlet_name'], $_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
} else {
    // Handle missing session variables case
    echo "<script>alert('User session is not properly set. Please log in again.');</script>";
    exit;
}

// Fetch customer name suggestions based on query
if (isset($_GET['customer_name'])) {
    $customerName = $connection->real_escape_string($_GET['customer_name']);
    $sql = "SELECT cr_name, cr_id, phone_number FROM credit_note WHERE cr_name LIKE '%$customerName%' LIMIT 5";

    $result = $connection->query($sql);
    $suggestions = "";

    while ($row = $result->fetch_assoc()) {
        $suggestions .= "<div class='dropdown-item' data-customer-name='" . $row['cr_name'] . "' data-customer-id='" . $row['cr_id'] . "' data-customer-phone='" . $row['phone_number'] . "'>" . $row['cr_name'] . "</div>";
    }

    echo $suggestions;
    exit;
}

// Get the school_name and class_name from the $_GET method
$customer_name = isset($_GET['class_name']) ? trim($_GET['class_name']) : '';
$customer_name2 = isset($_GET['school_name']) ? trim($_GET['school_name']) : '';

// Initialize total price
$totalPrice = 0;

// Fetch data from the database
$rec1 = mysqli_query($connection, "SELECT * FROM courses WHERE class_name = '$customer_name' AND school_name = '$customer_name2'");
if ($rec1) {
    while ($row1 = mysqli_fetch_array($rec1)) {
        $totalPrice += $row1['price']; // Add each course price to the total
    }
}

// Handle course sales submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_course'])) {
    
    $billAmount = $_POST['bill_amount'];
    $discountAmount = $_POST['discount_amount'];
    $discountPercentage = $_POST['discount_per'];
    $cashReceived = $_POST['cash_received'];
    $changeAmount = $_POST['change_amount'];
    $customerName = $_POST['customer_name'];
    $customerType = $_POST['customer_type'];
    $customerId = $_POST['customer_id'];
    $customerPhone = $_POST['customer_phone'];
$disc = $totalPrice - $billAmount;
    // Generate a single order ID for all entries
    $orderId = uniqid("ORDER");
    $date_time = date("Y-m-d");

    // Fetch all products to insert into log_user_sales
    $rec = mysqli_query($connection, "SELECT * FROM courses WHERE class_name = '$customer_name' AND school_name = '$customer_name2'");
    if ($rec) {
        while ($row = mysqli_fetch_assoc($rec)) {
            // Prepare product details for insertion
            $productId = $row['id'];
            $supplierName = $row['publisher'] ?? ''; // Default to empty if not available
            $company = $row['company'];
            $productName = $row['course_name'];
            $productPrice = $row['price'];
            $tradePrice = $row['trade_price'] ?? 0; // Default to 0 if not available
            $productQuantity = 1; // Assuming quantity is 1 for all courses
            $productTotal = $productPrice * $productQuantity;
            $totalAmount = $productPrice * $productQuantity;
            $bonus = 0; // Assuming no bonus
            $tax = 0; // Assuming no tax
            $taxAmount = 0; // Assuming no tax amount
            $saleCost = $productPrice; // Assuming sale cost is product price
            $schoolPer = $row['percentage'] ?? 0; // Default to 0 if not available
            $schoolAmount = $row['per_amount'] ?? 0; // Default to 0 if not available
            $rOrderId = ''; // Assuming no return order ID
            $status = ''; // Status of the sale

            // Insert each product into log_user_sales with the same order_id
            $insertQuery = "INSERT INTO log_user_sales 
                (product_id, supplier_name, company, product_name, product_price, trade_price, product_quantity, product_total, bonus, discount, tax, net_amount, tax_amount, total_amount, paid_by, sale_cost, customer_id, customer_type, customer_name, customer_phone, discount_amount, discounted, discount_per, cash_amount, change_amount, school_per, school_amount, order_id, r_order_id, status, outlet_name, login_user, user_role, outlet_address, date_time)
                VALUES 
                ('$productId', '$supplierName', '$company', '$productName', '$productPrice', '$tradePrice', '$productQuantity', '$productTotal', '$bonus', '', '$tax', '$productTotal', '$taxAmount', '$totalAmount', 'Cash', '$saleCost', '$customerId', '$customerType', '$customerName', '$customerPhone', '$billAmount', '$discountAmount', '$discountPercentage', '$cashReceived', '$changeAmount', '$schoolPer', '$schoolAmount', '$orderId', '$rOrderId', '$status', '$outlet_name', '$userName', '$userRole', '$outlet_address', '$date_time')";

            if (!mysqli_query($connection, $insertQuery)) {
                echo "<script>alert('Error inserting product: " . mysqli_error($connection) . "');</script>";
                exit;
            }
        }

        // Success message
        echo "<script>alert('Invoice generated successfully!');</script>";
        echo "<script type='text/javascript'>window.location.href = 'printpos.php?order_id=$orderId';</script>";
    } else {
        echo "<script>alert('Error fetching products: " . mysqli_error($connection) . "');</script>";
    }
}

?>



<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Courses - Detail</title>
    <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
<link rel="stylesheet" href="css/custom_css.css" />


</head>

<style>
 #table-container-wrapper {
    max-height: 400px; /* Adjust the maximum height as needed */
    overflow-y: auto; /* Enable vertical scroll when content overflows */
}
/* Custom styles for sidebar */    /* Custom styles for sidebar */
    .sidebar {
        width: 100px;
        background: linear-gradient(360deg, #060606, #3C2F23);
        position: fixed;
        bottom: 0;
        top: 60px;
        transition: transform 0.3s ease-in-out;
        transform: translateX(0);
        z-index: 1;
        height: 100%;
        border-radius: 0px;
		   transition: transform 0.3s ease-in-out, width 0.3s ease-in-out;
    }.sidebar.hide {
      transform: translateX(-100px); /* Move sidebar out of the viewport when it is hidden */
    }
      .sidebar .nav-item {
    padding: 10px 0 ;
    text-align: center;
    position: relative;
	font-size:12px;
}
    .sidebar .nav-link {
      color: #fff;
      position: relative; /* Ensure icon and text are positioned relative to the nav link */
      z-index: 2; /* Ensure the text and icon are above the hover background */
    }
    .sidebar .nav-link i {
      margin-bottom: 5px; /* Adjust the margin of the icon */
    }
    /* Custom styles for hover effect */
    .sidebar .nav-item:hover:after {
      background-color: #fff;
      content: '';
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 100%;
      z-index: 1; /* Ensure the hover background is below the text and icon */
    }
    .sidebar .nav-item:hover .nav-link {
      color: #503F2E;
    }
    /* Custom styles for divider */
    .sidebar .nav-item:after {
      content: "";
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      height: 1px;
      background-color: #fff;
      transition: height 0.3s ease-in-out; /* Transition effect for smooth animation */
    }
    /* Custom styles for header */ 
	   .header {
        background: linear-gradient(270deg, #060606, #3C2F23);
        color: #fff;
        padding: 10px;
        position: fixed;
        top: 0;
        width: 100%;
        z-index: 2;
        height: 69px;
        box-shadow: #FFF 2px 0px 0px 0px;
        /* Ensure header appears above sidebar */
    }
    .header .navbar-toggler {
      color: #fff;
    }
    .header .navbar-toggler-icon {
      color: #fff; /* Set the color of the toggle button to white */
    }
    .header .navbar-toggler.white {
      color: #fff !important; /* Ensure the toggle button is white */
    }
    .header .navbar-brand {
      color: #fff; /* Set navbar brand text color to white */
    }
    .header .nav-item .nav-link {
      color: #fff; /* Set nav link text color to white */
    }
    .main-content {
      margin-top: 50px; /* Height of fixed header + padding */
      margin-left: 100px; /* Width of sidebar */
      padding-top: 30px; /* Height of fixed header */
    }
	/* Custom styles for search bar */
    .search-container {
      display: flex;
      align-items: center;
      width: 300px;
      margin: 2px auto;
    }
    .search-input {
      width: 100%;
      padding: 10px 30px 10px 10px; /* Adjust padding to accommodate the icon */
      border: 1px solid #ccc;
      border-radius: 20px;
      font-size: 16px;
    }
    .search-icon {
      position: relative;
      left: -25px; /* Adjust the position of the icon */
      color: #aaa;
    }
    .search-icon i {
      position: absolute;
      top: 50%;
      transform: translateY(-50%);
    }
.btn-dark
         {
			 background:#503F2E;
			 color:#fff;
			 border: 1px solid #503F2E;
                 	}
		.btn-dark:hover{
			background:#fff;
			 color:#503F2E;
			 border:1px solid #503F2E;
			}	
			.bg-dark2{
			background:#503F2E;
			color:#fff;	
				}	
	
	 .modal-content {
            animation: modal-animation 0.5s;
        }

        @keyframes modal-animation {
            from {
                opacity: 0;
                transform: scale(0.8);
            }
            to {
                opacity: 1;
                transform: scale(1);
            }
        }
		
.dropdown-menu {
            max-height: 200px;
            overflow-y: auto;
            position: absolute;
            z-index: 1000;
            width: 100%;
        }
        .input-group {
            position: relative;
        }
		.dropdown-item.active, .dropdown-item:active {
    color: #fff;
    text-decoration: none;
    background-color: #0A5064;
}
</style>

<body>
<?php

?>
<?php include("common/hd.php");?>
<!-- Sidebar -->
<?php include("common/sd.php"); ?>
<div class="main-content">
<form action="sale_course.php?class_name=<?php echo $customer_name; ?>&&school_name=<?php echo $customer_name2; ?>" method="post">
<div class="contanier">
    <?php
            $rec = mysqli_query($connection,"select * from courses where class_name = '$customer_name' && school_name = '$customer_name2' ");
            ?>
            <br><br>
            <div class="row">
                
                <div class="col-sm-1"></div>
    <div class="col-sm-10">
        <h3>Complete Course</h3>
        <div class="row" style="background:#F0F0F0; padding:10px; border:1px solid #CCC;">
                    
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label>School Name</label>
                            <input type="text" id="customer_type" name="customer_type" class="form-control in_form" autocomplete="off"
                            value="<?php  echo $customer_name2; ?>" readonly>
                     
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label>Customer Name</label>
                            <input type="text" id="customer_name" name="customer_name" class="form-control in_form" autocomplete="off">
                            <div class="dropdown-menu" id="customer_suggestions"></div>
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label>Customer Phone</label>
                            <input type="text" id="customer_phone" name="customer_phone" class="form-control in_form">
                        </div>
                    </div>
                    
                     <div class="">
                        <div class="">
                            <label></label>
                            <input type="hidden" id="r_order_id" name="r_order_id" class="form-control in_form">
                            <div id="order_suggestions" class="dropdown-menu" style="display: none;"></div>
                        </div>
                    </div>
                    <div class="col-sm-3">
                        <div class="form-group">
                            <label>Customer ID</label>
                            <input type="text" id="customer_id" name="customer_id" class="form-control in_form">
                        </div>
                    </div>
                </div>
        
        
        <br>
        <table id="tableToPrint" class="table table-stripped table-hover text-center text-uppercase">
        <tr class="bg-dark text-white" style="font-size:14px;">
           
            <th>Sr#</th>
            <th>Class Name</th>
            <th>Subject</th>
            <th>Company</th>
            <th>Supplier</th>
            <th>T.P(Rs)</th>
           <th>Percentage</th>
            <th>(%) Amount</th>
            <th>Price(Rs)</th>
         
        </tr>
        
        <?php 
        $sr_no = 1;
        while($row = mysqli_fetch_array($rec)){
            $school_name = $row["school_name"];
        ?>
        <tr>
     
            <td><?php echo $sr_no++; ?></td>
            <td><?php echo $row["class_name"]; ?></td>
            <td style="color:#000;font-weight:700;">
            <?php echo $row["course_name"]; ?></td>
            <td><?php echo $row["company"]; ?></td>
            <td><?php echo $row["publisher"]; ?></td>
             <td><?php echo $row["trade_price"]; ?></td>
           <td><?php echo $row["percentage"]; ?></td>
            <td><?php echo $row["per_amount"]; ?></td>
            <td><?php echo $row["price"]; ?></td>
            
        </tr>
        <?php
        }
        ?>
    </table>
     <div class="row" style="padding:20px; background:#f3f3f3;">
        <div class="col-sm-2">
            <div class="form-group">
                <label>Total</label>
                <input type="text" name="total_amount" class="form-control" id="total_amount" value="<?php echo $totalPrice; ?>" readonly>
            </div>
        </div>
        <div class="col-sm-2">
            <div class="form-group">
                <label>Bill Amount</label>
                <input type="text" name="bill_amount" class="form-control" id="bill_amount">
            </div>
        </div>
        <div class="col-sm-2">
            <div class="form-group">
                <label>Discount</label>
                <input type="text" name="discount_amount" class="form-control" id="discount_amount" readonly>
            </div>
        </div>
        <div class="col-sm-2">
            <div class="form-group">
                <label>Discount Percentage</label>
                <input type="text" name="discount_per" class="form-control" id="discount_per" readonly>
            </div>
        </div>
        <div class="col-sm-2">
            <div class="form-group">
                <label>Cash Received</label>
                <input type="text" name="cash_received" class="form-control" id="cash_received">
            </div>
        </div>
        <div class="col-sm-2">
            <div class="form-group">
                <label>Change Amount</label>
                <input type="text" name="change_amount" class="form-control" id="change_amount" readonly>
            </div>
        </div>
        <div class="col-sm-2">
            <div class="form-group">
                <label>S.Tax</label>
                <input type="text" name="tax" class="form-control" id="tax" readonly>
            </div>
        </div>
        <div class="col-sm-2">
            <div class="form-group">
                <button type="submit" class="btn btn-dark" name="add_course" style="margin-top:30px;">Generate Invoice</button>
            </div>
        </div>
    </div>
    </div>
    <div class="col-sm-1"></div>
    </div>
</div>

<div class="" style="margin-top:30px;">
   
</div>
</form>

</div>    
</body>

<script>
    document.getElementById("customer_name").addEventListener("input", function() {
        var customerName = this.value;
        if (customerName.length > 0) {
            var xhr = new XMLHttpRequest();
            xhr.open("GET", "?customer_name=" + customerName, true);
            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var suggestions = document.getElementById("customer_suggestions");
                    suggestions.innerHTML = xhr.responseText;
                    suggestions.style.display = 'block';
                }
            };
            xhr.send();
        } else {
            document.getElementById("customer_suggestions").style.display = 'none';
        }
    });

    document.getElementById("customer_suggestions").addEventListener("click", function(e) {
        if (e.target && e.target.classList.contains("dropdown-item")) {
            selectCustomer(e.target);
        }
    });

    document.getElementById("customer_name").addEventListener("keydown", function(e) {
        var suggestions = document.getElementById("customer_suggestions");
        if (suggestions.style.display === 'block') {
            var items = suggestions.getElementsByClassName("dropdown-item");
            if (e.key === "ArrowDown") {
                currentFocus++;
                addActive(items);
            } else if (e.key === "ArrowUp") {
                currentFocus--;
                addActive(items);
            } else if (e.key === "Enter") {
                e.preventDefault();
                if (currentFocus > -1) {
                    if (items[currentFocus]) {
                        selectCustomer(items[currentFocus]);
                    }
                }
            }
        }
    });

    function addActive(items) {
        if (!items) return false;
        removeActive(items);
        if (currentFocus >= items.length) currentFocus = 0;
        if (currentFocus < 0) currentFocus = items.length - 1;
        items[currentFocus].classList.add("active");
        items[currentFocus].scrollIntoView({ block: "nearest" });
    }

    function removeActive(items) {
        for (var i = 0; i < items.length; i++) {
            items[i].classList.remove("active");
        }
    }

    function selectCustomer(item) {
        var customerName = item.getAttribute('data-customer-name');
        var customerId = item.getAttribute('data-customer-id');
        var customerPhone = item.getAttribute('data-customer-phone');

        document.getElementById("customer_name").value = customerName;
        document.getElementById("customer_phone").value = customerPhone;
        document.getElementById("customer_id").value = customerId;

        document.getElementById("customer_suggestions").style.display = 'none';
    }


    // Function to calculate discounts and change
    function calculate() {
        const totalAmount = parseFloat(document.getElementById('total_amount').value) || 0;
        const billAmount = parseFloat(document.getElementById('bill_amount').value) || 0;
        const cashReceived = parseFloat(document.getElementById('cash_received').value) || 0;

        // Calculate discount amount and percentage
        const discountAmount = totalAmount - billAmount;
        const discountPercentage = totalAmount > 0 ? (discountAmount / totalAmount) * 100 : 0;

        // Calculate change amount
        const changeAmount = cashReceived - billAmount;

        // Update the values in the form
        document.getElementById('discount_amount').value = discountAmount.toFixed(2);
        document.getElementById('discount_per').value = discountPercentage.toFixed(2);
        document.getElementById('change_amount').value = changeAmount.toFixed(2);
    }

    // Trigger calculate function on input changes
    document.getElementById('bill_amount').addEventListener('input', calculate);
    document.getElementById('cash_received').addEventListener('input', calculate);
</script>

</script>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</html>