<?php
session_start();
if(!isset($_SESSION['username'])) {
    header("Location: ../login.php");
    exit();
}

include('../includes/db.php');

$success_message = "";
$error_message = "";
$cart_items = isset($_SESSION['lube_purchase_cart']) ? $_SESSION['lube_purchase_cart'] : [];

// Get suppliers for dropdown
$suppliers_sql = "SELECT id, name FROM suppliers ORDER BY name";
$suppliers_result = mysqli_query($conn, $suppliers_sql);

// Get products for dropdown
$products_sql = "SELECT id, product_code, product_name, purchase_price, sale_price FROM lube_products WHERE status='active' ORDER BY product_name";
$products_result = mysqli_query($conn, $products_sql);

// Get bank accounts for dropdown
$bank_accounts_sql = "SELECT id, bank_name, account_title, balance FROM bank_accounts ORDER BY bank_name";
$bank_accounts_result = mysqli_query($conn, $bank_accounts_sql);

// Add to cart
if(isset($_POST['add_to_cart'])) {
    $product_id = intval($_POST['product_id']);
    $quantity = floatval($_POST['quantity']);
    $purchase_price = floatval($_POST['purchase_price']);
    
    if($product_id > 0 && $quantity > 0) {
        $prod_sql = "SELECT product_code, product_name FROM lube_products WHERE id=$product_id";
        $prod_result = mysqli_query($conn, $prod_sql);
        $product = mysqli_fetch_assoc($prod_result);
        
        $cart_items[] = [
            'product_id' => $product_id,
            'product_code' => $product['product_code'],
            'product_name' => $product['product_name'],
            'quantity' => $quantity,
            'purchase_price' => $purchase_price,
            'total' => $quantity * $purchase_price
        ];
        $_SESSION['lube_purchase_cart'] = $cart_items;
        $success_message = "Product added to cart!";
        header("Location: lube_purchase.php");
        exit();
    }
}

// Remove from cart
if(isset($_GET['remove'])) {
    $index = intval($_GET['remove']);
    if(isset($cart_items[$index])) {
        unset($cart_items[$index]);
        $_SESSION['lube_purchase_cart'] = array_values($cart_items);
        header("Location: lube_purchase.php");
        exit();
    }
}

// Clear cart
if(isset($_GET['clear_cart'])) {
    $_SESSION['lube_purchase_cart'] = [];
    header("Location: lube_purchase.php");
    exit();
}

// Calculate totals
$subtotal = 0;
foreach($cart_items as $item) {
    $subtotal += $item['total'];
}
$discount = isset($_POST['discount']) ? floatval($_POST['discount']) : 0;
$total_amount = $subtotal - $discount;

// Save purchase
if(isset($_POST['save_purchase'])) {
    $supplier_id = intval($_POST['supplier_id']);
    $purchase_invoice = mysqli_real_escape_string($conn, $_POST['purchase_invoice']);
    $purchase_date = mysqli_real_escape_string($conn, $_POST['purchase_date']);
    $discount = floatval($_POST['discount']);
    $payment_type = mysqli_real_escape_string($conn, $_POST['payment_type']);
    $bank_id = isset($_POST['bank_id']) ? intval($_POST['bank_id']) : 0;
    $notes = mysqli_real_escape_string($conn, $_POST['notes']);
    $created_by = $_SESSION['username'];
    $created_at = date('Y-m-d H:i:s');
    
    if(empty($cart_items)) {
        $error_message = "Please add at least one product to cart!";
    } elseif(empty($supplier_id)) {
        $error_message = "Please select a supplier!";
    } elseif($payment_type == 'bank' && empty($bank_id)) {
        $error_message = "Please select a bank account for bank payment!";
    } else {
        mysqli_begin_transaction($conn);
        try {
            if($payment_type == 'bank' && $bank_id > 0) {
                $bank_check_sql = "SELECT balance FROM bank_accounts WHERE id = $bank_id";
                $bank_check_result = mysqli_query($conn, $bank_check_sql);
                $bank_data = mysqli_fetch_assoc($bank_check_result);
                if($bank_data['balance'] < $total_amount) {
                    throw new Exception("Insufficient bank balance! Available: Rs " . number_format($bank_data['balance'], 2));
                }
            }
            
            $purchase_sql = "INSERT INTO lube_purchases (purchase_invoice, supplier_id, purchase_date, subtotal, discount, total_amount, payment_type, notes, created_by, created_at) 
                            VALUES ('$purchase_invoice', $supplier_id, '$purchase_date', $subtotal, $discount, $total_amount, '$payment_type', '$notes', '$created_by', '$created_at')";
            mysqli_query($conn, $purchase_sql);
            $purchase_id = mysqli_insert_id($conn);
            
            foreach($cart_items as $item) {
                $item_sql = "INSERT INTO lube_purchase_items (purchase_id, product_id, quantity, purchase_price, total) 
                            VALUES ($purchase_id, {$item['product_id']}, {$item['quantity']}, {$item['purchase_price']}, {$item['total']})";
                mysqli_query($conn, $item_sql);
                
                $update_stock = "UPDATE lube_products SET current_stock = current_stock + {$item['quantity']} WHERE id = {$item['product_id']}";
                mysqli_query($conn, $update_stock);
                
                $movement_sql = "INSERT INTO stock_movements (product_id, movement_type, reference_no, quantity_in, quantity_out, balance_stock, date_time, user_name) 
                                SELECT {$item['product_id']}, 'purchase', '$purchase_invoice', {$item['quantity']}, 0, current_stock, '$created_at', '$created_by' 
                                FROM lube_products WHERE id = {$item['product_id']}";
                mysqli_query($conn, $movement_sql);
            }
            
            $update_supplier_sql = "UPDATE suppliers SET current_balance = current_balance + $total_amount WHERE id = $supplier_id";
            mysqli_query($conn, $update_supplier_sql);
            
            if($payment_type == 'credit') {
                $payment_sql = "INSERT INTO supplier_payments (supplier_id, amount, payment_method, notes, date_time) 
                                VALUES ($supplier_id, $total_amount, 'purchase', 'Purchase Invoice: $purchase_invoice', '$created_at')";
                mysqli_query($conn, $payment_sql);
            }
            
            if($payment_type == 'bank' && $bank_id > 0) {
                $update_bank = "UPDATE bank_accounts SET balance = balance - $total_amount WHERE id = $bank_id";
                mysqli_query($conn, $update_bank);
                
                $bank_book_sql = "INSERT INTO bank_book (bank_id, entry_type, amount, description, reference_no, date_time) 
                                  VALUES ($bank_id, 'Withdrawal', $total_amount, 'Lube Purchase - Invoice: $purchase_invoice', '$purchase_invoice', '$created_at')";
                mysqli_query($conn, $bank_book_sql);
            }
            
            mysqli_commit($conn);
            $_SESSION['lube_purchase_cart'] = [];
            $success_message = "Purchase saved successfully! Invoice #: $purchase_invoice";
            
        } catch(Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}
?>

<?php include('../includes/log.php'); ?>
<?php include('../includes/sd.php'); ?>

<div class="lube-purchase-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-shopping-cart"></i> Lube Purchase</h2>
            <p>Record lubricant purchases from suppliers</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-truck"></i>
                <span>New Purchase</span>
            </div>
        </div>
    </div>

    <!-- Alerts -->
    <?php if($success_message): ?>
        <div class="alert-custom alert-success">
            <i class="fas fa-check-circle"></i> <?php echo $success_message; ?>
            <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
        </div>
    <?php endif; ?>
    
    <?php if($error_message): ?>
        <div class="alert-custom alert-danger">
            <i class="fas fa-exclamation-triangle"></i> <?php echo $error_message; ?>
            <button class="close-alert" onclick="this.parentElement.remove();">&times;</button>
        </div>
    <?php endif; ?>

    <div class="purchase-grid">
        <!-- Left Side - Product Selection -->
        <div class="product-selection-card">
            <div class="card-header-custom">
                <i class="fas fa-plus-circle"></i>
                <h4>Add Products</h4>
            </div>
            <div class="card-body-custom">
                <form method="POST" action="" id="addProductForm">
                    <div class="form-group-custom">
                        <label><i class="fas fa-box"></i> Select Product</label>
                        <select name="product_id" id="product_id" class="form-control-modern" required onchange="updateProductPrice()">
                            <option value="">-- Select Product --</option>
                            <?php 
                            mysqli_data_seek($products_result, 0);
                            while($prod = mysqli_fetch_assoc($products_result)): 
                            ?>
                                <option value="<?php echo $prod['id']; ?>" 
                                        data-price="<?php echo $prod['purchase_price']; ?>"
                                        data-name="<?php echo htmlspecialchars($prod['product_name']); ?>">
                                    <?php echo htmlspecialchars($prod['product_code']) . ' - ' . htmlspecialchars($prod['product_name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="form-row-custom">
                        <div class="form-group-custom half">
                            <label><i class="fas fa-balance-scale"></i> Quantity</label>
                            <input type="number" step="0.01" name="quantity" id="quantity" class="form-control-modern" required value="1" onkeyup="updateTotal()">
                        </div>
                        <div class="form-group-custom half">
                            <label><i class="fas fa-rupee-sign"></i> Purchase Price</label>
                            <input type="number" step="0.01" name="purchase_price" id="purchase_price" class="form-control-modern" required onkeyup="updateTotal()">
                        </div>
                    </div>
                    
                    <div class="form-group-custom">
                        <label><i class="fas fa-calculator"></i> Total</label>
                        <input type="text" id="item_total" class="form-control-modern" readonly style="background:#f0f0f0; font-weight:bold;">
                    </div>
                    
                    <button type="submit" name="add_to_cart" class="btn-add-cart">
                        <i class="fas fa-cart-plus"></i> Add to Cart
                    </button>
                </form>
            </div>
        </div>

        <!-- Right Side - Cart & Purchase Details -->
        <div class="cart-card">
            <div class="card-header-custom">
                <i class="fas fa-shopping-cart"></i>
                <h4>Purchase Cart</h4>
                <?php if(count($cart_items) > 0): ?>
                    <a href="?clear_cart=1" class="btn-clear" onclick="return confirm('Clear entire cart?')">
                        <i class="fas fa-trash-alt"></i> Clear Cart
                    </a>
                <?php endif; ?>
            </div>
            <div class="card-body-custom">
                <?php if(count($cart_items) > 0): ?>
                    <div class="cart-table-container">
                        <table class="cart-table">
                            <thead>
                                <tr>
                                    <th>Product</th>
                                    <th width="15%">Qty</th>
                                    <th width="15%">Price</th>
                                    <th width="15%">Total</th>
                                    <th width="8%"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach($cart_items as $index => $item): ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($item['product_name']); ?> <br>
                                            <small><?php echo $item['product_code']; ?></small>
                                         </div>
                                        <td>
                                            <input type="number" step="0.01" value="<?php echo $item['quantity']; ?>" 
                                                   class="cart-qty" data-index="<?php echo $index; ?>" style="width:70px;">
                                         </div>
                                        <td>Rs <?php echo number_format($item['purchase_price'], 2); ?></div>
                                        <td><strong>Rs <?php echo number_format($item['total'], 2); ?></strong></div>
                                        <td>
                                            <a href="?remove=<?php echo $index; ?>" class="btn-remove" onclick="return confirm('Remove item?')">
                                                <i class="fas fa-times"></i>
                                            </a>
                                         </div>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                            <tfoot>
                                <tr class="subtotal-row">
                                    <td colspan="3" class="text-right"><strong>Subtotal:</strong></td>
                                    <td><strong>Rs <?php echo number_format($subtotal, 2); ?></strong></td>
                                    <td></div>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                    
                    <form method="POST" action="" class="purchase-form" id="purchaseForm">
                        <div class="form-row-custom">
                            <div class="form-group-custom half">
                                <label><i class="fas fa-file-invoice"></i> Invoice No *</label>
                                <input type="text" name="purchase_invoice" class="form-control-modern" required 
                                       value="PO-<?php echo date('YmdHis'); ?>">
                            </div>
                            <div class="form-group-custom half">
                                <label><i class="fas fa-calendar"></i> Purchase Date *</label>
                                <input type="date" name="purchase_date" class="form-control-modern" required 
                                       value="<?php echo date('Y-m-d'); ?>">
                            </div>
                        </div>

                        <div class="form-group-custom">
                            <label><i class="fas fa-truck"></i> Supplier *</label>
                            <select name="supplier_id" id="supplier_id" class="form-control-modern" required>
                                <option value="">-- Select Supplier --</option>
                                <?php 
                                mysqli_data_seek($suppliers_result, 0);
                                while($sup = mysqli_fetch_assoc($suppliers_result)): 
                                ?>
                                    <option value="<?php echo $sup['id']; ?>"><?php echo htmlspecialchars($sup['name']); ?></option>
                                <?php endwhile; ?>
                            </select>
                        </div>

                        <div class="form-group-custom">
                            <label><i class="fas fa-credit-card"></i> Payment Type</label>
                            <select name="payment_type" id="payment_type" class="form-control-modern" onchange="toggleBankField()">
                                <option value="credit">Credit</option>
                                <option value="cash">Cash</option>
                                <option value="bank">Bank Transfer</option>
                            </select>
                        </div>

                        <!-- Bank Account Selection -->
                        <div class="form-group-custom" id="bank_div" style="display: none;">
                            <label><i class="fas fa-university"></i> Select Bank Account *</label>
                            <select name="bank_id" id="bank_id" class="form-control-modern" onchange="updateBankInfo()">
                                <option value="">-- Select Bank Account --</option>
                                <?php 
                                mysqli_data_seek($bank_accounts_result, 0);
                                while($bank = mysqli_fetch_assoc($bank_accounts_result)): 
                                ?>
                                    <option value="<?php echo $bank['id']; ?>"
                                            data-bank-balance="<?php echo $bank['balance']; ?>">
                                        <?php echo htmlspecialchars($bank['bank_name']); ?> - 
                                        <?php echo htmlspecialchars($bank['account_title']); ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>

                        <!-- Bank Info Box -->
                        <div class="bank-info-box" id="bankInfoBox" style="display: none;">
                            <div class="info-row">
                                <span><i class="fas fa-university"></i> Bank Balance:</span>
                                <strong id="displayBankBalance">Rs 0.00</strong>
                            </div>
                            <div class="info-row">
                                <span><i class="fas fa-arrow-down"></i> After Payment:</span>
                                <strong id="displayNewBankBalance">Rs 0.00</strong>
                            </div>
                        </div>

                        <div class="form-row-custom">
                            <div class="form-group-custom half">
                                <label><i class="fas fa-percent"></i> Discount (Rs)</label>
                                <input type="number" step="0.01" name="discount" id="discount" class="form-control-modern" value="0" onkeyup="updateGrandTotal()">
                            </div>
                            <div class="form-group-custom half">
                                <label><i class="fas fa-rupee-sign"></i> Grand Total</label>
                                <input type="text" id="grand_total" class="form-control-modern" readonly style="background:#f0f0f0; font-weight:bold; color:#A04657;">
                            </div>
                        </div>

                        <div class="form-group-custom">
                            <label><i class="fas fa-sticky-note"></i> Notes</label>
                            <textarea name="notes" class="form-control-modern" rows="2" placeholder="Optional notes..."></textarea>
                        </div>

                        <button type="submit" name="save_purchase" class="btn-save">
                            <i class="fas fa-save"></i> Save Purchase
                        </button>
                    </form>
                    
                <?php else: ?>
                    <div class="empty-cart">
                        <i class="fas fa-shopping-cart"></i>
                        <p>Cart is empty</p>
                        <small>Add products from the left panel</small>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<style>
/* Lube Purchase Styles - Page Specific Only */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');

* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
    font-family: 'Poppins', sans-serif;
}

body {
    background: #f5f7fb;
    overflow-x: hidden;
}

h1, h2, h3, h4, h5, h6,
.page-header h2,
.card-header-custom h4 {
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}

/* Main Content */
.main-content {
    margin-left: 280px;
    padding: 15px 20px;
    transition: all 0.3s;
    background: #f5f7fb;
}

.lube-purchase-container {
    max-width: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}

/* Page Header */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 16px;
    padding: 16px 24px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    width: 100%;
}

.page-header h2 {
    margin: 0 0 3px 0;
    font-size: 22px;
}

.page-header p {
    margin: 0;
    font-size: 12px;
    opacity: 0.9;
}

.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 6px 16px;
    border-radius: 12px;
    font-weight: 500;
    font-size: 12px;
}

/* Purchase Grid */
.purchase-grid {
    display: grid;
    grid-template-columns: 380px 1fr;
    gap: 20px;
    width: 100%;
}

/* Product Selection Card */
.product-selection-card, .cart-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.04);
    border: 1px solid #f0f0f0;
}

.card-header-custom {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    padding: 14px 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    color: #fff;
}

.card-header-custom h4 {
    margin: 0;
    font-size: 15px;
    flex: 1;
}

.btn-clear {
    background: rgba(255,255,255,0.2);
    padding: 4px 10px;
    border-radius: 20px;
    font-size: 11px;
    color: #fff;
    text-decoration: none;
}

.btn-clear:hover {
    background: rgba(255,255,255,0.35);
}

.card-body-custom {
    padding: 20px;
}

.form-group-custom {
    margin-bottom: 16px;
}

.form-group-custom label {
    display: block;
    margin-bottom: 6px;
    font-weight: 600;
    font-size: 12px;
    color: #555;
}

.form-group-custom label i {
    color: #A04657;
    margin-right: 5px;
}

.form-control-modern {
    width: 100%;
    padding: 9px 12px;
    border: 2px solid #e8e8e8;
    border-radius: 10px;
    font-size: 13px;
    transition: all 0.3s;
    background: #fafafa;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
    background: #fff;
}

.form-row-custom {
    display: flex;
    gap: 12px;
}

.half {
    flex: 1;
}

.btn-add-cart {
    width: 100%;
    padding: 11px;
    background: linear-gradient(135deg, #A04657, #6b2a36);
    color: #fff;
    border: none;
    border-radius: 10px;
    font-weight: 600;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 13px;
}

.btn-add-cart:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(160,70,87,0.3);
}

/* Cart Card */
.cart-table-container {
    overflow-x: auto;
    margin-bottom: 18px;
    width: 100%;
}

.cart-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
}

.cart-table th {
    padding: 10px 12px;
    background: #f8f9fc;
    font-size: 11px;
    font-weight: 700;
    text-align: left;
    border-bottom: 2px solid #e8e8e8;
    color: #555;
}

.cart-table td {
    padding: 10px 12px;
    border-bottom: 1px solid #f0f0f0;
    font-size: 12px;
    vertical-align: middle;
}

.cart-qty {
    padding: 4px 8px;
    border: 1px solid #ddd;
    border-radius: 8px;
    text-align: center;
    font-size: 12px;
}

.btn-remove {
    color: #dc3545;
    text-decoration: none;
    font-size: 14px;
}

.btn-remove:hover {
    color: #a71d2a;
    transform: scale(1.1);
}

.subtotal-row {
    background: #f8f9fc;
    font-weight: 600;
}

.text-right {
    text-align: right;
}

.empty-cart {
    text-align: center;
    padding: 40px;
}

.empty-cart i {
    font-size: 48px;
    color: #A04657;
    opacity: 0.3;
    margin-bottom: 12px;
    display: block;
}

.empty-cart p {
    font-size: 13px;
    color: #666;
}

.btn-save {
    width: 100%;
    padding: 12px;
    background: linear-gradient(135deg, #28a745, #1e7e34);
    color: #fff;
    border: none;
    border-radius: 10px;
    font-weight: 700;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    font-size: 14px;
}

.btn-save:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(40,167,69,0.3);
}

/* Alerts */
.alert-custom {
    padding: 12px 18px;
    border-radius: 12px;
    margin-bottom: 18px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 13px;
    width: 100%;
}

.alert-success {
    background: #e8f5e9;
    color: #2e7d32;
    border-left: 4px solid #28a745;
}

.alert-danger {
    background: #ffebee;
    color: #c62828;
    border-left: 4px solid #dc3545;
}

.close-alert {
    background: none;
    border: none;
    font-size: 18px;
    cursor: pointer;
    opacity: 0.6;
}

.close-alert:hover {
    opacity: 1;
}

.bank-info-box {
    background: #e3f2fd;
    padding: 10px 14px;
    border-radius: 10px;
    margin-bottom: 14px;
    border-left: 4px solid #1976d2;
}

.bank-info-box .info-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 6px;
    font-size: 12px;
}

.bank-info-box .info-row:last-child {
    margin-bottom: 0;
}

/* Responsive */
@media (max-width: 1100px) {
    .purchase-grid {
        grid-template-columns: 1fr;
        gap: 16px;
    }
}

@media (max-width: 992px) {
    .main-content {
        margin-left: 0;
        padding: 12px 15px;
    }
}

@media (max-width: 768px) {
    .main-content {
        padding: 10px 12px;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 10px;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .form-row-custom {
        flex-direction: column;
        gap: 0;
    }
    .card-body-custom {
        padding: 16px;
    }
    .cart-table th, .cart-table td {
        padding: 8px 10px;
        font-size: 11px;
    }
    .empty-cart {
        padding: 30px;
    }
    .empty-cart i {
        font-size: 40px;
    }
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 10px;
}

::-webkit-scrollbar-thumb:hover {
    background: #6b2a36;
}
</style>

<script>
function updateProductPrice() {
    let select = document.getElementById('product_id');
    let selected = select.options[select.selectedIndex];
    let price = selected.getAttribute('data-price');
    if(price) {
        document.getElementById('purchase_price').value = price;
        updateTotal();
    }
}

function updateTotal() {
    let qty = parseFloat(document.getElementById('quantity').value) || 0;
    let price = parseFloat(document.getElementById('purchase_price').value) || 0;
    let total = qty * price;
    document.getElementById('item_total').value = 'Rs ' + total.toFixed(2);
}

function updateGrandTotal() {
    let subtotal = <?php echo $subtotal; ?>;
    let discount = parseFloat(document.getElementById('discount').value) || 0;
    let grandTotal = subtotal - discount;
    document.getElementById('grand_total').value = 'Rs ' + grandTotal.toFixed(2);
    updateBankInfo();
}

function toggleBankField() {
    let paymentType = document.getElementById('payment_type').value;
    let bankDiv = document.getElementById('bank_div');
    let bankInfoBox = document.getElementById('bankInfoBox');
    
    if(paymentType === 'bank') {
        bankDiv.style.display = 'block';
        bankInfoBox.style.display = 'block';
        document.getElementById('bank_id').setAttribute('required', 'required');
        updateBankInfo();
    } else {
        bankDiv.style.display = 'none';
        bankInfoBox.style.display = 'none';
        document.getElementById('bank_id').removeAttribute('required');
    }
}

function updateBankInfo() {
    let paymentType = document.getElementById('payment_type').value;
    if(paymentType !== 'bank') return;
    
    let bankSelect = document.getElementById('bank_id');
    let selectedOption = bankSelect.options[bankSelect.selectedIndex];
    let bankBalance = selectedOption.getAttribute('data-bank-balance') || 0;
    let grandTotalText = document.getElementById('grand_total').value;
    let grandTotal = parseFloat(grandTotalText.replace('Rs ', '')) || 0;
    
    document.getElementById('displayBankBalance').innerHTML = 'Rs ' + parseFloat(bankBalance).toFixed(2);
    
    let newBalance = parseFloat(bankBalance) - grandTotal;
    let newBalanceSpan = document.getElementById('displayNewBankBalance');
    newBalanceSpan.innerHTML = 'Rs ' + newBalance.toFixed(2);
    
    if(grandTotal > bankBalance) {
        newBalanceSpan.style.color = '#dc3545';
        newBalanceSpan.innerHTML += ' (Insufficient!)';
    } else {
        newBalanceSpan.style.color = '#28a745';
    }
}

<?php if($subtotal > 0): ?>
document.getElementById('grand_total').value = 'Rs <?php echo number_format($total_amount, 2); ?>';
<?php endif; ?>

document.querySelectorAll('.alert-custom').forEach(alert => {
    setTimeout(() => {
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 300);
    }, 5000);
});

document.getElementById('bank_id')?.addEventListener('change', updateBankInfo);
</script>

<?php include('../includes/ft.php'); ?>