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

if (isset($_SESSION['user_name']) && isset($_SESSION['user_role']) && isset($_SESSION['outlet_name']) && isset($_SESSION['outlet_address'])) {
    $userName = $_SESSION['user_name'];
    $userRole = $_SESSION['user_role'];
    $outlet_address = $_SESSION['outlet_address'];
    $outlet_name = $_SESSION['outlet_name'];
} else {
    echo "<script>window.location.href = 'logout.php';</script>";
    exit;
}

function generateOrderId(mysqli $connection): string {
    $connection->query("INSERT INTO order_sequence () VALUES ()");
    return str_pad($connection->insert_id, 5, "0", STR_PAD_LEFT);
}

if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
}

// Product search
if (isset($_GET['query'])) {
    $query = $connection->real_escape_string($_GET['query']);
    $sql = "SELECT product_id, product_name, retail_price, trade_price, category, supplier, company, product_unit, quantity FROM products WHERE product_name LIKE '%$query%'";
    $result = $connection->query($sql);
    $suggestions = "";
    while ($row = $result->fetch_assoc()) {
        $suggestions .= "<div class='suggestion-item' data-product-id='" . $row['product_id'] . "' data-category='" . $row['category'] . "' data-product-quantity='" . $row['quantity'] . "' data-retail-price='" . $row['retail_price'] . "' data-trade-price='" . $row['trade_price'] . "' data-supplier='" . $row['supplier'] . "' data-company='" . $row['company'] . "'>" . $row['product_name'] . "</div>";
    }
    echo $suggestions;
    exit;
}

// Customer search
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()) {
        $crName = $row['cr_name'];
        $crId = $row['cr_id'];
        $phone = $row['phone_number'];
        $remainSql = "SELECT remain_balance FROM creditor_closing WHERE creditor_name = '$crName' ORDER BY id DESC LIMIT 1";
        $remainResult = $connection->query($remainSql);
        $remainBalance = "0";
        if ($remainResult && $remainResult->num_rows > 0) {
            $remainRow = $remainResult->fetch_assoc();
            $remainBalance = $remainRow['remain_balance'];
        }
        $suggestions .= "<div class='suggestion-item' data-customer-name='$crName' data-customer-id='$crId' data-customer-phone='$phone' data-remain-balance='$remainBalance'>$crName</div>";
    }
    echo $suggestions;
    exit;
}

$user = $userName;
$role = $userRole;
$outlet = $outlet_name;
$address = $outlet_address;

// Process sale
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["bill"])) {
    if ($connection->connect_error) {
        die("Connection failed: " . $connection->connect_error);
    }

    $productData = json_decode($_POST['productData'], true);
    $orderId = generateOrderId($connection);
    $paidBy = $_POST['method'];
    $bill_amount = $_POST["BillAmount"];
    $discount_amount = $_POST["bill_amount"];
    $discounted = $_POST["discount_amount"];
    $discount_per = $_POST["discount_percent"];
    $cash_amount = $_POST["cash_received"];
    $change_amount = $_POST["cash_return"];
    $customerName = $_POST["customer_name"];
    $customerPhone = $_POST["customer_phone"];
    $customer_type = $_POST["customer_type"];
    $customer_id = $_POST["customer_id"];
    $r_order_id = $_POST["r_order_id"];
    $pre_amount = $_POST["pre_amount"];
    $grand_amount = $_POST["grand_amount"];
    $desc_note = $_POST['desc_note'];
    $date_time = date("Y-m-d");

    foreach ($productData as $product) {
        $productId = $product['productId'];
        $category = $product['category'];
        $productName = $product['description'];
        $productPrice = $product['pricePerUnit'];
        $tradePrice = $product['tradePrice'];
        $productQuantity = $product['quantity'];
        $productTotal = $product['totalPrice'];
        $discount = $product['discountPercentage'];
        $discAmount = $product['discAmount'];
        $tax = $product['tax'];
        $netAmount = $product['netAmount'];
        $supplierName = $product['supplier'];
        $company = $product['company'];
        $sale_cost = $tradePrice * $productQuantity;
        $tp = $sale_cost;
        
        $sql = "INSERT INTO log_user_sales (
            product_id, supplier_name, company, category, product_name,
            product_price, trade_price, product_quantity, product_total,
            bonus, discount, disc_amount, tax, net_amount,
            BillAmount, total_amount, pre_amount, grand_amount,
            paid_by, sale_cost, customer_id, customer_type,
            customer_name, customer_phone, discount_amount,
            discounted, discount_per, cash_amount, change_amount,
            order_id, r_order_id, outlet_name, login_user,
            user_role, outlet_address, date_time, desc_note
        ) VALUES (
            '$productId', '$supplierName', '$company', '$category', '$productName',
            '$productPrice', '$tradePrice', '$productQuantity', '$productTotal',
            '', '$discount', '$discAmount', '$tax', '$netAmount',
            '$bill_amount', '$productTotal', '$pre_amount', '$grand_amount',
            '$paidBy', '$sale_cost', '$customer_id', '$customer_type',
            '$customerName', '$customerPhone', '$discount_amount',
            '$discounted', '$discount_per', '$cash_amount', '$change_amount',
            '$orderId', '$r_order_id', '$outlet', '$user',
            '$role', '$address', '$date_time', '$desc_note'
        )";
        
        if ($connection->query($sql) !== TRUE) {
            echo "Error: " . $sql . "<br>" . $connection->error;
            ob_end_flush();
            exit;
        }
        
        $updateSql = "UPDATE products SET quantity = quantity - $productQuantity, total_amount = total_amount - $tp WHERE product_id = '$productId'";
        if ($connection->query($updateSql) !== TRUE) {
            throw new Exception("Error updating product quantity: " . $connection->error);
        }
    }

    ob_end_clean();
    echo "<script type='text/javascript'>window.location.href = 'printtypep.php?order_id=$orderId';</script>";
}

ob_end_flush();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title><?php echo $tx; ?> | Point of Sale</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    
    <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 href="https://fonts.googleapis.com/css2?family=Quicksand:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Quicksand', sans-serif;
            background: #f5f7fb;
        }
        
        /* Header */
        .app-header {
            background: #0A4657;
            padding: 12px 24px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        .app-header .logo-area {
            display: flex;
            align-items: center;
            gap: 12px;
        }
        
        .app-header .logo-img {
            width: 48px;
            height: 48px;
            background: white;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 6px;
        }
        
        .app-header .logo-img img {
            width: 100%;
            height: auto;
        }
        
        .app-header .store-name {
            color: white;
            font-size: 1.3rem;
            font-weight: 700;
            margin: 0;
        }
        
        .btn-back {
            background: rgba(255,255,255,0.15);
            border: none;
            color: white;
            padding: 8px 18px;
            border-radius: 30px;
            font-size: 0.8rem;
            font-weight: 600;
            transition: all 0.2s;
        }
        
        .btn-back:hover {
            background: rgba(255,255,255,0.25);
            color: white;
            text-decoration: none;
        }
        
        /* Cards */
        .card-pos {
            background: white;
            border-radius: 20px;
            border: none;
            box-shadow: 0 2px 12px rgba(0,0,0,0.05);
            margin-bottom: 20px;
            overflow: hidden;
        }
        
        .card-header-pos {
            background: white;
            padding: 16px 20px;
            border-bottom: 2px solid #eef2f6;
        }
        
        .card-header-pos h5 {
            margin: 0;
            font-size: 1rem;
            font-weight: 700;
            color: #0A4657;
        }
        
        .card-body-pos {
            padding: 20px;
        }
        
        /* Form Elements */
        .form-group {
            margin-bottom: 16px;
        }
        
        .form-label {
            font-size: 0.7rem;
            font-weight: 700;
            text-transform: uppercase;
            color: #6c757d;
            letter-spacing: 0.5px;
            margin-bottom: 6px;
            display: block;
        }
        
        .form-control-pos {
            width: 100%;
            padding: 12px 14px;
            font-size: 0.9rem;
            font-weight: 500;
            font-family: 'Quicksand', sans-serif;
            border: 1.5px solid #e2e8f0;
            border-radius: 14px;
            transition: all 0.2s;
            background: white;
        }
        
        .form-control-pos:focus {
            outline: none;
            border-color: #0A4657;
            box-shadow: 0 0 0 3px rgba(10,70,87,0.1);
        }
        
        .form-control-pos[readonly] {
            background: #f8f9fc;
            cursor: default;
        }
        
        select.form-control-pos {
            cursor: pointer;
        }
        
        /* Input Group */
        .input-group-pos {
            display: flex;
            align-items: stretch;
        }
        
        .input-group-pos .input-group-text {
            background: #f8f9fc;
            border: 1.5px solid #e2e8f0;
            border-right: none;
            border-radius: 14px 0 0 14px;
            font-size: 0.7rem;
            font-weight: 700;
            color: #0A4657;
            padding: 0 14px;
        }
        
        .input-group-pos .form-control-pos {
            border-radius: 0 14px 14px 0;
            border-left: none;
        }
        
        /* Buttons */
        .btn-add-cart {
            background: #0A4657;
            color: white;
            border: none;
            border-radius: 14px;
            padding: 12px;
            font-weight: 700;
            font-size: 0.9rem;
            width: 100%;
            transition: all 0.2s;
            margin-top: 8px;
        }
        
        .btn-add-cart:hover {
            background: #063544;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(10,70,87,0.3);
        }
        
        .btn-refresh {
            background: #eef2f6;
            color: #1a2a3a;
            border: none;
            border-radius: 14px;
            padding: 10px;
            font-weight: 600;
            font-size: 0.8rem;
            width: 100%;
            transition: all 0.2s;
        }
        
        .btn-refresh:hover {
            background: #e2e8f0;
        }
        
        .btn-view-sales {
            background: transparent;
            border: 1.5px solid #0A4657;
            color: #0A4657;
            border-radius: 14px;
            padding: 10px;
            font-weight: 600;
            font-size: 0.8rem;
            width: 100%;
            transition: all 0.2s;
            display: inline-block;
            text-align: center;
        }
        
        .btn-view-sales:hover {
            background: #0A4657;
            color: white;
            text-decoration: none;
        }
        
        .btn-generate {
            background: #0A4657;
            color: white;
            border: none;
            border-radius: 40px;
            padding: 14px 32px;
            font-weight: 700;
            font-size: 1rem;
            transition: all 0.2s;
        }
        
        .btn-generate:hover {
            background: #063544;
            transform: translateY(-1px);
            box-shadow: 0 6px 16px rgba(10,70,87,0.3);
        }
        
        /* Table */
        .table-wrapper {
            max-height: 320px;
            overflow-y: auto;
            border-radius: 16px;
        }
        
        .cart-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .cart-table th {
            background: #0A4657;
            color: white;
            padding: 12px 8px;
            font-size: 0.7rem;
            font-weight: 600;
            text-align: center;
            position: sticky;
            top: 0;
            white-space: nowrap;
        }
        
        .cart-table td {
            padding: 10px 8px;
            font-size: 0.75rem;
            font-weight: 500;
            text-align: center;
            border-bottom: 1px solid #eef2f6;
            vertical-align: middle;
        }
        
        .cart-table tr:hover {
            background: #f8f9fc;
        }
        
        .action-btn {
            padding: 6px 10px;
            border-radius: 10px;
            font-size: 0.7rem;
            font-weight: 600;
            border: none;
            margin: 0 3px;
            transition: all 0.2s;
        }
        
        .btn-delete {
            background: #fee2e2;
            color: #dc2626;
        }
        
        .btn-delete:hover {
            background: #dc2626;
            color: white;
        }
        
        .btn-edit {
            background: #e0f2fe;
            color: #0284c7;
        }
        
        .btn-edit:hover {
            background: #0284c7;
            color: white;
        }
        
        /* Row with 2 columns layout */
        .split-layout {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
        }
        
        .split-left {
            flex: 1.2;
            min-width: 280px;
        }
        
        .split-right {
            flex: 2;
            min-width: 450px;
        }
        
        /* Row fields */
        .row-fields {
            display: flex;
            gap: 12px;
            margin-bottom: 12px;
        }
        
        .row-fields .field {
            flex: 1;
        }
        
        /* Suggestions */
        .suggestions-dropdown {
            position: absolute;
            background: white;
            border-radius: 14px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.12);
            max-height: 250px;
            overflow-y: auto;
            z-index: 1000;
            width: calc(100% - 28px);
            margin-top: 4px;
        }
        
        .suggestion-item {
            padding: 12px 16px;
            font-size: 0.85rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            border-bottom: 1px solid #eef2f6;
        }
        
        .suggestion-item:hover {
            background: rgba(10,70,87,0.08);
            color: #0A4657;
        }
        
        /* Position relative for dropdown */
        .pos-relative {
            position: relative;
        }
        
        /* Responsive */
        @media (max-width: 900px) {
            .split-layout {
                flex-direction: column;
            }
            .split-right {
                min-width: auto;
            }
            .app-header .store-name {
                font-size: 1rem;
            }
        }
        
        hr {
            margin: 16px 0;
            border-color: #eef2f6;
        }
        
        textarea.form-control-pos {
            resize: vertical;
        }
    </style>
</head>
<body>

<!-- Header -->
<div class="app-header">
    <div class="container-fluid">
        <div class="row align-items-center">
            <div class="col-6">
                <div class="logo-area">
                    <div class="logo-img">
                        <img src="../img/logo231.png" alt="Logo">
                    </div>
                    <h1 class="store-name"><?php echo $tx; ?></h1>
                </div>
            </div>
            <div class="col-6 text-right">
                <a href="addproduct.php" class="btn-back">
                    <i class="fas fa-arrow-left mr-2"></i> Back
                </a>
            </div>
        </div>
    </div>
</div>

<div class="container-fluid py-4">
    <form action="mainpos.php" method="post" enctype="multipart/form-data">
        <div class="split-layout">
            <!-- LEFT PANEL - Add Product -->
            <div class="split-left">
                <div class="card-pos">
                    <div class="card-header-pos">
                        <h5><i class="fas fa-plus-circle mr-2"></i> Add Product</h5>
                    </div>
                    <div class="card-body-pos">
                        <!-- Product Search -->
                        <div class="pos-relative">
                            <div class="form-group">
                                <label class="form-label">🔍 Search Product</label>
                                <input type="text" id="productInput" class="form-control-pos" placeholder="Type product name..." autocomplete="off">
                                <div id="suggestions" class="suggestions-dropdown" style="display: none;"></div>
                            </div>
                        </div>
                        
                        <div class="row-fields">
                            <div class="field">
                                <label class="form-label">💰 Price</label>
                                <input type="text" id="p_price" class="form-control-pos" readonly>
                            </div>
                            <div class="field">
                                <label class="form-label">📦 Stock</label>
                                <input type="text" id="remain_quantity" class="form-control-pos" readonly>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">🔢 Quantity</label>
                            <input type="number" id="quantity" class="form-control-pos" placeholder="Enter quantity">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">💵 Unit Price</label>
                            <input type="text" id="retail_price" class="form-control-pos" placeholder="Price per unit">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">💰 Total Amount</label>
                            <input type="text" id="total_amount" class="form-control-pos" readonly>
                        </div>
                        
                        <div class="row-fields">
                            <div class="field">
                                <label class="form-label">📉 Discount %</label>
                                <input type="text" id="percentage" class="form-control-pos" placeholder="0">
                            </div>
                            <div class="field">
                                <label class="form-label">📉 Discount (PKR)</label>
                                <input type="text" id="disc_amount" class="form-control-pos" placeholder="0">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">✅ Net Amount</label>
                            <input type="text" id="trade_price" class="form-control-pos" readonly>
                        </div>
                        
                        <button type="button" class="btn-add-cart" id="makeEntry">
                            <i class="fas fa-cart-plus mr-2"></i> Add to Cart
                        </button>
                        
                        <hr>
                        
                        <div class="row-fields">
                            <div class="field">
                                <button type="button" class="btn-refresh" onclick="location.reload();">
                                    <i class="fas fa-sync-alt mr-2"></i> Refresh
                                </button>
                            </div>
                            <div class="field">
                                <a href="order_detail_v.php" class="btn-view-sales">
                                    <i class="fas fa-eye mr-2"></i> View Sales
                                </a>
                            </div>
                        </div>
                        
                        <hr>
                        
                        <div class="form-group">
                            <label class="form-label">📝 Note</label>
                            <textarea name="desc_note" class="form-control-pos" rows="3" placeholder="Add note about this sale..."></textarea>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- RIGHT PANEL - Customer & Cart -->
            <div class="split-right">
                <!-- Customer Info -->
                <div class="card-pos">
                    <div class="card-header-pos">
                        <h5><i class="fas fa-user mr-2"></i> Customer Information</h5>
                    </div>
                    <div class="card-body-pos">
                        <div class="row-fields">
                            <div class="field">
                                <label class="form-label">👤 Customer Name</label>
                                <div class="pos-relative">
                                    <input type="text" id="customer_name" name="customer_name" class="form-control-pos" placeholder="Enter customer name" autocomplete="off">
                                    <div id="customer_suggestions" class="suggestions-dropdown" style="display: none;"></div>
                                </div>
                            </div>
                            <div class="field">
                                <label class="form-label">📞 Phone Number</label>
                                <input type="text" id="customer_phone" name="customer_phone" class="form-control-pos" placeholder="Customer phone">
                            </div>
                            <div class="field">
                                <label class="form-label">💳 Payment Method</label>
                                <select name="method" id="method" class="form-control-pos">
                                    <option value="cash">💰 Cash</option>
                                    <option value="credit">💳 Credit</option>
                                    <option value="bank1">🏦 Bank 1</option>
                                    <option value="bank2">🏦 Bank 2</option>
                                    <option value="bank3">🏦 Bank 3</option>
                                    <option value="others">🔄 Others</option>
                                </select>
                            </div>
                        </div>
                        <input type="hidden" id="customer_id" name="customer_id">
                        <input type="hidden" id="customer_type" name="customer_type" value="walkin">
                        <input type="hidden" id="r_order_id" name="r_order_id">
                    </div>
                </div>
                
                <!-- Cart Table -->
                <div class="card-pos">
                    <div class="card-header-pos">
                        <h5><i class="fas fa-shopping-cart mr-2"></i> Shopping Cart</h5>
                    </div>
                    <div class="card-body-pos">
                        <div class="table-wrapper">
                            <table class="cart-table" id="productsTable">
                                <thead>
                                    <tr>
                                        <th>Code</th>
                                        <th>Product</th>
                                        <th>Qty</th>
                                        <th>Price</th>
                                        <th>Amount</th>
                                        <th>Dis%</th>
                                        <th>Net</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <!-- Dynamic rows -->
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                
                <!-- Checkout -->
                <div class="card-pos">
                    <div class="card-header-pos">
                        <h5><i class="fas fa-receipt mr-2"></i> Checkout Summary</h5>
                    </div>
                    <div class="card-body-pos">
                        <div class="row-fields">
                            <div class="field">
                                <label class="form-label">Total Amount</label>
                                <input type="text" id="total-input" name="total_input" class="form-control-pos" readonly>
                            </div>
                            <div class="field">
                                <label class="form-label">Bill Amount</label>
                                <input type="text" id="bill-amount" name="bill_amount" class="form-control-pos" required>
                            </div>
                            <div class="field">
                                <label class="form-label">Previous Due</label>
                                <input type="text" id="pre_amount" name="pre_amount" class="form-control-pos" readonly>
                            </div>
                            <div class="field">
                                <label class="form-label">Grand Total</label>
                                <input type="text" id="grand_amount" name="grand_amount" class="form-control-pos" readonly>
                            </div>
                        </div>
                        <div class="row-fields">
                            <div class="field">
                                <label class="form-label">Discount (PKR)</label>
                                <input type="number" id="discount_amount" name="discount_amount" class="form-control-pos" value="0">
                            </div>
                            <div class="field">
                                <label class="form-label">Discount %</label>
                                <input type="number" id="discount_percent" name="discount_percent" class="form-control-pos" readonly>
                            </div>
                            <div class="field">
                                <label class="form-label">Cash Received</label>
                                <input type="number" id="cash_received" name="cash_received" class="form-control-pos">
                            </div>
                            <div class="field">
                                <label class="form-label">Change Amount</label>
                                <input type="number" id="cash_return" name="cash_return" class="form-control-pos" readonly>
                            </div>
                        </div>
                        <hr>
                        <div class="text-center">
                            <button type="submit" name="bill" class="btn-generate">
                                <i class="fas fa-file-invoice mr-2"></i> Generate Invoice
                            </button>
                        </div>
                        <input type="hidden" id="productData" name="productData">
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
// Payment method handler
document.getElementById("method").addEventListener("change", function() {
    const cashInput = document.getElementById("cash_received");
    if (this.value === "credit") {
        cashInput.readOnly = true;
        cashInput.value = "";
    } else {
        cashInput.readOnly = false;
    }
});

// Credit validation
document.querySelector("button[name='bill']").addEventListener("click", function(e) {
    const method = document.getElementById("method").value;
    const customerName = document.getElementById("customer_name").value.trim();
    if (method === "credit" && customerName === "") {
        e.preventDefault();
        alert("⚠️ Please enter Customer Name for Credit payment.");
    }
});

// Product search
let currentFocus = -1;
const productInput = document.getElementById("productInput");

productInput.addEventListener("input", function() {
    let query = this.value;
    if (query.length > 0) {
        fetch("?query=" + encodeURIComponent(query))
            .then(res => res.text())
            .then(html => {
                document.getElementById("suggestions").innerHTML = html;
                document.getElementById("suggestions").style.display = "block";
            });
    } else {
        document.getElementById("suggestions").style.display = "none";
    }
});

document.getElementById("suggestions").addEventListener("click", function(e) {
    if (e.target.classList.contains("suggestion-item")) {
        selectProduct(e.target);
    }
});

function selectProduct(item) {
    productInput.value = item.textContent;
    document.getElementById("remain_quantity").value = item.dataset.productQuantity;
    document.getElementById("p_price").value = item.dataset.tradePrice;
    document.getElementById("retail_price").value = item.dataset.retailPrice;
    productInput.dataset.productId = item.dataset.productId;
    productInput.dataset.supplier = item.dataset.supplier;
    productInput.dataset.company = item.dataset.company;
    productInput.dataset.category = item.dataset.category;
    productInput.dataset.tradePrice = item.dataset.tradePrice;
    document.getElementById("suggestions").style.display = "none";
    calculateTotalPrice();
}

// Customer search
const customerInput = document.getElementById("customer_name");
customerInput.addEventListener("input", function() {
    let name = this.value;
    if (name.length > 0) {
        fetch("?customer_name=" + encodeURIComponent(name))
            .then(res => res.text())
            .then(html => {
                document.getElementById("customer_suggestions").innerHTML = html;
                document.getElementById("customer_suggestions").style.display = "block";
            });
    } else {
        document.getElementById("customer_suggestions").style.display = "none";
    }
});

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

function selectCustomer(item) {
    document.getElementById("customer_name").value = item.dataset.customerName;
    document.getElementById("customer_phone").value = item.dataset.customerPhone;
    document.getElementById("customer_id").value = item.dataset.customerId;
    document.getElementById("pre_amount").value = item.dataset.remainBalance;
    document.getElementById("customer_suggestions").style.display = "none";
    updateGrandAmount();
}

// Calculations
function calculateTotalPrice() {
    let qty = parseFloat(document.getElementById("quantity").value) || 0;
    let price = parseFloat(document.getElementById("retail_price").value) || 0;
    let total = qty * price;
    let discPercent = parseFloat(document.getElementById("percentage").value) || 0;
    let discAmount = parseFloat(document.getElementById("disc_amount").value) || 0;
    
    if (total > 0) {
        if (discPercent > 0) {
            discAmount = (total * discPercent) / 100;
            document.getElementById("disc_amount").value = discAmount.toFixed(0);
        } else if (discAmount > 0) {
            discPercent = (discAmount * 100) / total;
            document.getElementById("percentage").value = discPercent.toFixed(2);
        }
    }
    
    let net = total - discAmount;
    if (net < 0) net = 0;
    
    document.getElementById("total_amount").value = total.toFixed(2);
    document.getElementById("trade_price").value = net.toFixed(2);
}

["quantity", "retail_price", "percentage", "disc_amount"].forEach(id => {
    document.getElementById(id).addEventListener("input", calculateTotalPrice);
});

// Add to cart
document.getElementById("makeEntry").addEventListener("click", function() {
    const productId = productInput.dataset.productId;
    const description = productInput.value;
    const qty = parseFloat(document.getElementById("quantity").value) || 0;
    const price = parseFloat(document.getElementById("retail_price").value) || 0;
    const total = parseFloat(document.getElementById("total_amount").value) || 0;
    const discPercent = parseFloat(document.getElementById("percentage").value) || 0;
    const discAmount = parseFloat(document.getElementById("disc_amount").value) || 0;
    const net = parseFloat(document.getElementById("trade_price").value) || 0;
    const supplier = productInput.dataset.supplier || "";
    const company = productInput.dataset.company || "";
    const tradePrice = productInput.dataset.tradePrice || 0;
    const category = productInput.dataset.category || "";
    
    if (!productId || !description || qty <= 0) {
        alert("⚠️ Select a product and enter valid quantity!");
        return;
    }
    
    const tbody = document.querySelector("#productsTable tbody");
    const row = tbody.insertRow();
    row.innerHTML = `
        <td style="display:none;">${productId}</td>
        <td style="display:none;">${supplier}</td>
        <td style="display:none;">${company}</td>
        <td style="display:none;">${tradePrice}</td>
        <td style="display:none;">${category}</td>
        <td>${productId.substring(0,6)}</td>
        <td style="text-align:left; font-weight:600;">${description.substring(0,25)}</td>
        <td>${qty}</td>
        <td>${price}</td>
        <td>${total}</td>
        <td>${discPercent.toFixed(0)}</td>
        <td>${net}</td>
        <td>
            <button class="action-btn btn-edit" type="button"><i class="fas fa-edit"></i></button>
            <button class="action-btn btn-delete" type="button"><i class="fas fa-trash"></i></button>
        </td>
    `;
    
    row.querySelector(".btn-delete").addEventListener("click", () => {
        row.remove();
        calculateTotalAmount();
        updateProductData();
    });
    
    row.querySelector(".btn-edit").addEventListener("click", () => {
        const cells = row.querySelectorAll("td");
        productInput.value = cells[5].innerText;
        document.getElementById("quantity").value = cells[7].innerText;
        document.getElementById("retail_price").value = cells[8].innerText;
        document.getElementById("total_amount").value = cells[9].innerText;
        document.getElementById("percentage").value = cells[10].innerText;
        document.getElementById("trade_price").value = cells[11].innerText;
        row.remove();
        calculateTotalAmount();
        updateProductData();
        productInput.focus();
    });
    
    calculateTotalAmount();
    updateProductData();
    resetProductFields();
    productInput.focus();
});

function resetProductFields() {
    productInput.value = "";
    document.getElementById("remain_quantity").value = "";
    document.getElementById("quantity").value = "";
    document.getElementById("retail_price").value = "";
    document.getElementById("total_amount").value = "";
    document.getElementById("percentage").value = "";
    document.getElementById("disc_amount").value = "";
    document.getElementById("trade_price").value = "";
    document.getElementById("p_price").value = "";
    delete productInput.dataset.productId;
    delete productInput.dataset.supplier;
    delete productInput.dataset.company;
    delete productInput.dataset.category;
    delete productInput.dataset.tradePrice;
}

function calculateTotalAmount() {
    const rows = document.querySelectorAll("#productsTable tbody tr");
    let total = 0;
    rows.forEach(row => {
        let net = parseFloat(row.cells[11]?.innerText) || 0;
        total += net;
    });
    document.getElementById("total-input").value = total.toFixed(2);
    document.getElementById("bill-amount").value = total.toFixed(2);
    updateDiscountAmount();
    updateGrandAmount();
}

function updateDiscountAmount() {
    let total = parseFloat(document.getElementById("total-input").value) || 0;
    let bill = parseFloat(document.getElementById("bill-amount").value) || 0;
    let discAmount = total - bill;
    document.getElementById("discount_amount").value = Math.round(discAmount);
    let discPercent = total > 0 ? (discAmount / total) * 100 : 0;
    document.getElementById("discount_percent").value = discPercent.toFixed(2);
}

function updateGrandAmount() {
    let bill = parseFloat(document.getElementById("bill-amount").value) || 0;
    let pre = parseFloat(document.getElementById("pre_amount").value) || 0;
    document.getElementById("grand_amount").value = (bill + pre).toFixed(2);
    calculateCashReturn();
}

function calculateCashReturn() {
    let grand = parseFloat(document.getElementById("grand_amount").value) || 0;
    let received = parseFloat(document.getElementById("cash_received").value) || 0;
    document.getElementById("cash_return").value = (grand - received).toFixed(2);
}

function updateProductData() {
    const rows = document.querySelectorAll("#productsTable tbody tr");
    const productData = [];
    rows.forEach(row => {
        const cells = row.querySelectorAll("td");
        productData.push({
            productId: cells[0]?.innerText,
            description: cells[5]?.innerText,
            quantity: cells[7]?.innerText,
            pricePerUnit: cells[8]?.innerText,
            totalPrice: cells[9]?.innerText,
            discountPercentage: cells[10]?.innerText,
            discAmount: cells[11]?.innerText,
            tax: "0",
            netAmount: cells[11]?.innerText,
            supplier: cells[1]?.innerText,
            company: cells[2]?.innerText,
            tradePrice: cells[3]?.innerText,
            category: cells[4]?.innerText
        });
    });
    document.getElementById("productData").value = JSON.stringify(productData);
}

// Event listeners for checkout
["bill-amount", "pre_amount", "cash_received", "discount_amount"].forEach(id => {
    let el = document.getElementById(id);
    if (el) {
        el.addEventListener("input", function() {
            if (id === "discount_amount") {
                let total = parseFloat(document.getElementById("total-input").value) || 0;
                let disc = parseFloat(document.getElementById("discount_amount").value) || 0;
                document.getElementById("bill-amount").value = (total - disc).toFixed(2);
                let discPercent = total > 0 ? (disc / total) * 100 : 0;
                document.getElementById("discount_percent").value = discPercent.toFixed(2);
            }
            updateGrandAmount();
        });
    }
});

// Prevent form submit on Enter
document.querySelector("form").addEventListener("keydown", function(e) {
    if (e.key === "Enter" && e.target.type !== "submit") {
        e.preventDefault();
    }
});
</script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>