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

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

$success_message = "";
$error_message = "";

// Get fuel types with purchase price
$fuel_types_sql = "SELECT id, name, purchase_price, sale_price FROM fuel_types ORDER BY name";
$fuel_types_result = mysqli_query($conn, $fuel_types_sql);

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

// Get bank accounts
$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 Purchase
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_purchase'])) {
    $fuel_type_id = mysqli_real_escape_string($conn, $_POST['fuel_type_id']);
    $tank_id = mysqli_real_escape_string($conn, $_POST['tank_id']);
    $supplier_id = mysqli_real_escape_string($conn, $_POST['supplier_id']);
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $bank_id = isset($_POST['bank_id']) ? mysqli_real_escape_string($conn, $_POST['bank_id']) : '';
    $quantity = mysqli_real_escape_string($conn, $_POST['quantity']);
    $rate = mysqli_real_escape_string($conn, $_POST['rate']);
    $do_number = mysqli_real_escape_string($conn, $_POST['do_number']);
    $total_amount = $quantity * $rate;
    $date_time = date('Y-m-d H:i:s');
    
    if(empty($fuel_type_id) || empty($tank_id) || empty($supplier_id) || empty($quantity) || empty($rate) || empty($do_number)) {
        $error_message = "All fields are required!";
    } elseif(!is_numeric($quantity) || $quantity <= 0) {
        $error_message = "Quantity must be greater than 0!";
    } elseif(!is_numeric($rate) || $rate <= 0) {
        $error_message = "Rate must be greater than 0!";
    } elseif($payment_method == 'bank' && empty($bank_id)) {
        $error_message = "Please select a bank account for bank payment!";
    } else {
        mysqli_begin_transaction($conn);
        
        try {
            // Insert purchase record
            $sql = "INSERT INTO purchases (fuel_type_id, tank_id, supplier_id, payment_method, quantity, rate, total_amount, do_number, date_time) 
                    VALUES ('$fuel_type_id', '$tank_id', '$supplier_id', '$payment_method', '$quantity', '$rate', '$total_amount', '$do_number', '$date_time')";
            
            if(mysqli_query($conn, $sql)) {
                // Update tank stock
                $update_stock = "UPDATE tanks SET current_stock = current_stock + $quantity, purchase_stock = purchase_stock + $quantity WHERE id = '$tank_id'";
                mysqli_query($conn, $update_stock);
                
                // Update supplier balance (add to current balance for credit purchases)
                if($payment_method == 'credit') {
                    $update_supplier = "UPDATE suppliers SET current_balance = current_balance + $total_amount WHERE id = '$supplier_id'";
                    mysqli_query($conn, $update_supplier);
                }
                
                // For bank payment, deduct from bank account
                if($payment_method == 'bank' && !empty($bank_id)) {
                    // Get current bank balance
                    $bank_sql = "SELECT balance FROM bank_accounts WHERE id = '$bank_id'";
                    $bank_result = mysqli_query($conn, $bank_sql);
                    $bank_data = mysqli_fetch_assoc($bank_result);
                    
                    if($bank_data['balance'] < $total_amount) {
                        throw new Exception("Insufficient bank balance! Available: Rs " . number_format($bank_data['balance'], 2));
                    }
                    
                    // Update bank balance
                    $update_bank = "UPDATE bank_accounts SET balance = balance - $total_amount WHERE id = '$bank_id'";
                    mysqli_query($conn, $update_bank);
                    
                    // Insert into bank book
                    $bank_book_sql = "INSERT INTO bank_book (bank_id, entry_type, amount, description, reference_no, date_time) 
                                      VALUES ('$bank_id', 'Withdrawal', '$total_amount', 'Fuel Purchase - DO: $do_number', '$do_number', '$date_time')";
                    mysqli_query($conn, $bank_book_sql);
                }
                
                mysqli_commit($conn);
                
                if($payment_method == 'credit') {
                    $success_message = "Purchase added successfully! Amount added to supplier credit.";
                } elseif($payment_method == 'bank') {
                    $success_message = "Purchase added successfully! Payment made via bank account.";
                } else {
                    $success_message = "Purchase added successfully! Paid via cash.";
                }
            } else {
                throw new Exception("Failed to add purchase");
            }
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// Update Purchase (Edit)
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_purchase'])) {
    $purchase_id = mysqli_real_escape_string($conn, $_POST['purchase_id']);
    $fuel_type_id = mysqli_real_escape_string($conn, $_POST['fuel_type_id']);
    $tank_id = mysqli_real_escape_string($conn, $_POST['tank_id']);
    $supplier_id = mysqli_real_escape_string($conn, $_POST['supplier_id']);
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $bank_id = isset($_POST['bank_id']) ? mysqli_real_escape_string($conn, $_POST['bank_id']) : '';
    $quantity = mysqli_real_escape_string($conn, $_POST['quantity']);
    $rate = mysqli_real_escape_string($conn, $_POST['rate']);
    $do_number = mysqli_real_escape_string($conn, $_POST['do_number']);
    $total_amount = $quantity * $rate;
    
    // Get old purchase data
    $old_sql = "SELECT * FROM purchases WHERE id = '$purchase_id'";
    $old_result = mysqli_query($conn, $old_sql);
    $old_purchase = mysqli_fetch_assoc($old_result);
    
    if($old_purchase) {
        mysqli_begin_transaction($conn);
        
        try {
            // Reverse old tank stock
            $reverse_stock = "UPDATE tanks SET current_stock = current_stock - " . $old_purchase['quantity'] . ", purchase_stock = purchase_stock - " . $old_purchase['quantity'] . " WHERE id = '" . $old_purchase['tank_id'] . "'";
            mysqli_query($conn, $reverse_stock);
            
            // Reverse old supplier balance if credit
            if($old_purchase['payment_method'] == 'credit') {
                $reverse_supplier = "UPDATE suppliers SET current_balance = current_balance - " . $old_purchase['total_amount'] . " WHERE id = '" . $old_purchase['supplier_id'] . "'";
                mysqli_query($conn, $reverse_supplier);
            }
            
            // Reverse old bank payment if bank
            if($old_purchase['payment_method'] == 'bank') {
                // Delete old bank book entry
                $delete_bank_book = "DELETE FROM bank_book WHERE reference_no = '" . $old_purchase['do_number'] . "' AND entry_type = 'Withdrawal'";
                mysqli_query($conn, $delete_bank_book);
                
                // Reverse bank balance (add back)
                $find_bank_sql = "SELECT bank_id FROM bank_book WHERE reference_no = '" . $old_purchase['do_number'] . "' LIMIT 1";
                $find_bank_result = mysqli_query($conn, $find_bank_sql);
                if($find_bank_data = mysqli_fetch_assoc($find_bank_result)) {
                    $reverse_bank = "UPDATE bank_accounts SET balance = balance + " . $old_purchase['total_amount'] . " WHERE id = '" . $find_bank_data['bank_id'] . "'";
                    mysqli_query($conn, $reverse_bank);
                }
            }
            
            // Update purchase record
            $update_sql = "UPDATE purchases SET 
                          fuel_type_id = '$fuel_type_id',
                          tank_id = '$tank_id',
                          supplier_id = '$supplier_id',
                          payment_method = '$payment_method',
                          quantity = '$quantity',
                          rate = '$rate',
                          total_amount = '$total_amount',
                          do_number = '$do_number'
                          WHERE id = '$purchase_id'";
            
            if(mysqli_query($conn, $update_sql)) {
                // Apply new tank stock
                $apply_stock = "UPDATE tanks SET current_stock = current_stock + $quantity, purchase_stock = purchase_stock + $quantity WHERE id = '$tank_id'";
                mysqli_query($conn, $apply_stock);
                
                // Apply new supplier balance if credit
                if($payment_method == 'credit') {
                    $apply_supplier = "UPDATE suppliers SET current_balance = current_balance + $total_amount WHERE id = '$supplier_id'";
                    mysqli_query($conn, $apply_supplier);
                }
                
                // Apply new bank payment if bank
                if($payment_method == 'bank' && !empty($bank_id)) {
                    // Get current bank balance
                    $bank_sql = "SELECT balance FROM bank_accounts WHERE id = '$bank_id'";
                    $bank_result = mysqli_query($conn, $bank_sql);
                    $bank_data = mysqli_fetch_assoc($bank_result);
                    
                    if($bank_data['balance'] < $total_amount) {
                        throw new Exception("Insufficient bank balance! Available: Rs " . number_format($bank_data['balance'], 2));
                    }
                    
                    // Update bank balance
                    $update_bank = "UPDATE bank_accounts SET balance = balance - $total_amount WHERE id = '$bank_id'";
                    mysqli_query($conn, $update_bank);
                    
                    // Insert into bank book
                    $bank_book_sql = "INSERT INTO bank_book (bank_id, entry_type, amount, description, reference_no, date_time) 
                                      VALUES ('$bank_id', 'Withdrawal', '$total_amount', 'Fuel Purchase - DO: $do_number', '$do_number', NOW())";
                    mysqli_query($conn, $bank_book_sql);
                }
                
                mysqli_commit($conn);
                $success_message = "Purchase updated successfully!";
            } else {
                throw new Exception("Failed to update purchase");
            }
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// Delete Purchase
if(isset($_GET['delete'])) {
    $delete_id = mysqli_real_escape_string($conn, $_GET['delete']);
    
    // Get purchase details first
    $purchase_sql = "SELECT * FROM purchases WHERE id = '$delete_id'";
    $purchase_result = mysqli_query($conn, $purchase_sql);
    $purchase = mysqli_fetch_assoc($purchase_result);
    
    if($purchase) {
        mysqli_begin_transaction($conn);
        
        try {
            // Reverse tank stock
            $reverse_stock = "UPDATE tanks SET current_stock = current_stock - " . $purchase['quantity'] . ", purchase_stock = purchase_stock - " . $purchase['quantity'] . " WHERE id = '" . $purchase['tank_id'] . "'";
            mysqli_query($conn, $reverse_stock);
            
            // Reverse supplier balance if credit
            if($purchase['payment_method'] == 'credit') {
                $reverse_supplier = "UPDATE suppliers SET current_balance = current_balance - " . $purchase['total_amount'] . " WHERE id = '" . $purchase['supplier_id'] . "'";
                mysqli_query($conn, $reverse_supplier);
            }
            
            // Reverse bank payment if bank
            if($purchase['payment_method'] == 'bank') {
                $delete_bank_book = "DELETE FROM bank_book WHERE reference_no = '" . $purchase['do_number'] . "' AND entry_type = 'Withdrawal'";
                mysqli_query($conn, $delete_bank_book);
                
                // Find bank and reverse balance
                $find_bank_sql = "SELECT bank_id FROM bank_book WHERE reference_no = '" . $purchase['do_number'] . "' LIMIT 1";
                $find_bank_result = mysqli_query($conn, $find_bank_sql);
                if($find_bank_data = mysqli_fetch_assoc($find_bank_result)) {
                    $reverse_bank = "UPDATE bank_accounts SET balance = balance + " . $purchase['total_amount'] . " WHERE id = '" . $find_bank_data['bank_id'] . "'";
                    mysqli_query($conn, $reverse_bank);
                }
            }
            
            // Delete purchase
            $delete_sql = "DELETE FROM purchases WHERE id = '$delete_id'";
            mysqli_query($conn, $delete_sql);
            
            mysqli_commit($conn);
            $success_message = "Purchase deleted successfully! Stock and balances reversed.";
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    } else {
        $error_message = "Purchase not found!";
    }
    
    header("Location: purchases.php");
    exit();
}

// Get all purchases with details
$sql = "SELECT p.*, f.name as fuel_name, f.purchase_price, f.sale_price, t.tank_name, s.name as supplier_name
        FROM purchases p 
        LEFT JOIN fuel_types f ON p.fuel_type_id = f.id 
        LEFT JOIN tanks t ON p.tank_id = t.id 
        LEFT JOIN suppliers s ON p.supplier_id = s.id
        ORDER BY p.id DESC";
$result = mysqli_query($conn, $sql);

// Get purchase statistics
$total_purchases = mysqli_num_rows($result);
$total_quantity = 0;
$total_amount_sum = 0;

mysqli_data_seek($result, 0);
while($row = mysqli_fetch_assoc($result)) {
    $total_quantity += $row['quantity'];
    $total_amount_sum += $row['total_amount'];
}
mysqli_data_seek($result, 0);

// Get single purchase for edit
$edit_purchase = null;
if(isset($_GET['edit'])) {
    $edit_id = mysqli_real_escape_string($conn, $_GET['edit']);
    $edit_sql = "SELECT * FROM purchases WHERE id = '$edit_id'";
    $edit_result = mysqli_query($conn, $edit_sql);
    $edit_purchase = mysqli_fetch_assoc($edit_result);
}
?>

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

<div class="purchase-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-shopping-cart"></i> Fuel Purchase Management</h2>
            <p>Record fuel purchases, track inventory and manage supplier credits</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span><?php echo $total_purchases; ?> Total Purchases</span>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-tachometer-alt"></i></div>
            <div class="stat-info">
                <h3><?php echo number_format($total_quantity, 2); ?> L</h3>
                <p>Total Quantity</p>
                <span class="stat-trend">Fuel Purchased</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-rupee-sign"></i></div>
            <div class="stat-info">
                <h3>Rs <?php echo number_format($total_amount_sum, 2); ?></h3>
                <p>Total Amount</p>
                <span class="stat-trend">Total Investment</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-chart-line"></i></div>
            <div class="stat-info">
                <h3><?php echo $total_purchases; ?></h3>
                <p>Total Orders</p>
                <span class="stat-trend">Purchase Records</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="content-grid">
        <!-- Add/Edit Purchase Form -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fas fa-plus-circle"></i>
                <h4><?php echo isset($_GET['edit']) ? 'Edit Purchase' : 'Record New Purchase'; ?></h4>
            </div>
            <div class="form-card-body">
                <form method="POST" action="" id="purchaseForm">
                    <?php if(isset($_GET['edit']) && $edit_purchase): ?>
                        <input type="hidden" name="purchase_id" value="<?php echo $edit_purchase['id']; ?>">
                    <?php endif; ?>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-oil-can"></i> Fuel Type <span class="required">*</span></label>
                        <select name="fuel_type_id" id="fuel_type_id" class="form-control-modern" required>
                            <option value="">-- Select Fuel Type --</option>
                            <?php 
                            mysqli_data_seek($fuel_types_result, 0);
                            while($fuel = mysqli_fetch_assoc($fuel_types_result)): 
                                $selected = (isset($edit_purchase) && $edit_purchase['fuel_type_id'] == $fuel['id']) ? 'selected' : '';
                            ?>
                                <option value="<?php echo $fuel['id']; ?>" 
                                        data-purchase-price="<?php echo $fuel['purchase_price']; ?>"
                                        data-sale-price="<?php echo $fuel['sale_price']; ?>"
                                        <?php echo $selected; ?>>
                                    <?php echo htmlspecialchars($fuel['name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-tachometer-alt"></i> Select Tank <span class="required">*</span></label>
                        <select name="tank_id" id="tank_id" class="form-control-modern" required onchange="updateStockInfo()">
                            <option value="">-- Select Tank --</option>
                            <?php 
                            $tanks_sql = "SELECT t.id, t.tank_name, t.current_stock, t.capacity, f.name as fuel_name 
                                        FROM tanks t 
                                        LEFT JOIN fuel_types f ON t.fuel_type_id = f.id 
                                        ORDER BY f.name, t.tank_name";
                            $tanks_result = mysqli_query($conn, $tanks_sql);
                            while($tank = mysqli_fetch_assoc($tanks_result)): 
                                $selected = (isset($edit_purchase) && $edit_purchase['tank_id'] == $tank['id']) ? 'selected' : '';
                            ?>
                                <option value="<?php echo $tank['id']; ?>"
                                        data-fuel-name="<?php echo $tank['fuel_name']; ?>"
                                        data-current-stock="<?php echo $tank['current_stock']; ?>"
                                        data-capacity="<?php echo $tank['capacity']; ?>"
                                        <?php echo $selected; ?>>
                                    <?php echo htmlspecialchars($tank['tank_name']); ?> (<?php echo htmlspecialchars($tank['fuel_name']); ?>)
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-truck"></i> Select Supplier <span class="required">*</span></label>
                        <select name="supplier_id" id="supplier_id" class="form-control-modern" required onchange="updateSupplierBalance()">
                            <option value="">-- Select Supplier --</option>
                            <?php 
                            mysqli_data_seek($suppliers_result, 0);
                            while($supplier = mysqli_fetch_assoc($suppliers_result)): 
                                $selected = (isset($edit_purchase) && $edit_purchase['supplier_id'] == $supplier['id']) ? 'selected' : '';
                            ?>
                                <option value="<?php echo $supplier['id']; ?>"
                                        data-supplier-balance="<?php echo $supplier['current_balance']; ?>"
                                        <?php echo $selected; ?>>
                                    <?php echo htmlspecialchars($supplier['name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-credit-card"></i> Payment Method <span class="required">*</span></label>
                        <select name="payment_method" id="payment_method" class="form-control-modern" required onchange="updatePaymentMethod()">
                            <option value="credit" <?php echo (isset($edit_purchase) && $edit_purchase['payment_method'] == 'credit') ? 'selected' : ''; ?>>Credit (Add to Supplier Balance)</option>
                            <option value="cash" <?php echo (isset($edit_purchase) && $edit_purchase['payment_method'] == 'cash') ? 'selected' : ''; ?>>Cash (Paid Now)</option>
                            <option value="bank" <?php echo (isset($edit_purchase) && $edit_purchase['payment_method'] == 'bank') ? 'selected' : ''; ?>>Bank (Payment via Bank)</option>
                        </select>
                    </div>
                    
                    <!-- Bank Account Selection -->
                    <div class="input-group-custom" id="bank_account_div" style="display: none;">
                        <label><i class="fas fa-university"></i> Select Bank Account <span class="required">*</span></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>
                    
                    <div class="supplier-info-box" id="supplierInfoBox">
                        <div class="info-title"><i class="fas fa-info-circle"></i> Supplier Information</div>
                        <div class="info-row">
                            <span><i class="fas fa-rupee-sign"></i> Current Balance:</span>
                            <strong id="displaySupplierBalance" class="balance-amount">Rs 0.00</strong>
                        </div>
                        <div class="info-row highlight" id="newBalanceRow" style="display: none;">
                            <span><i class="fas fa-arrow-up"></i> New Balance after purchase:</span>
                            <strong id="displayNewSupplierBalance" class="due-amount">Rs 0.00</strong>
                        </div>
                    </div>
                    
                    <!-- Bank Info Box -->
                    <div class="info-box" id="bankInfoBox" style="display: none; background: #e3f2fd;">
                        <div class="info-title"><i class="fas fa-university"></i> Bank Information</div>
                        <div class="info-row">
                            <span><i class="fas fa-rupee-sign"></i> Selected Bank Balance:</span>
                            <strong id="displayBankBalance" class="balance-amount">Rs 0.00</strong>
                        </div>
                        <div class="info-row highlight" id="bankNewBalanceRow" style="display: none;">
                            <span><i class="fas fa-arrow-down"></i> New Bank Balance after payment:</span>
                            <strong id="displayNewBankBalance" style="color: #dc3545;">Rs 0.00</strong>
                        </div>
                    </div>
                    
                    <div class="row-inputs">
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-tachometer-alt"></i> Quantity (Liters) <span class="required">*</span></label>
                                <input type="number" step="0.01" name="quantity" id="quantity" class="form-control-modern" required 
                                       value="<?php echo isset($edit_purchase) ? $edit_purchase['quantity'] : ''; ?>"
                                       placeholder="Enter quantity" onkeyup="calculateTotal(); updateStockInfo()">
                            </div>
                        </div>
                        <div class="input-half">
                            <div class="input-group-custom">
                                <label><i class="fas fa-dollar-sign"></i> Rate (per Liter) <span class="required">*</span></label>
                                <input type="number" step="0.01" name="rate" id="rate" class="form-control-modern" required 
                                       value="<?php echo isset($edit_purchase) ? $edit_purchase['rate'] : ''; ?>"
                                       placeholder="Rate per liter" onkeyup="calculateTotal()">
                            </div>
                        </div>
                    </div>
                    
                    <div class="info-box">
                        <div class="info-title"><i class="fas fa-chart-line"></i> Tank Stock Info</div>
                        <div class="info-row">
                            <span><i class="fas fa-tachometer-alt"></i> Current Tank Stock:</span>
                            <strong id="displayCurrentStock">0 Liters</strong>
                        </div>
                        <div class="info-row highlight">
                            <span><i class="fas fa-arrow-up"></i> New Stock After Purchase:</span>
                            <strong id="displayNewStock" class="text-success">0 Liters</strong>
                        </div>
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-calculator"></i> Total Amount</label>
                        <input type="text" id="total_amount_display" class="form-control-modern total-amount" readonly>
                        <input type="hidden" name="total_amount" id="total_amount_hidden">
                    </div>
                    
                    <div class="input-group-custom">
                        <label><i class="fas fa-file-alt"></i> DO Number (Delivery Order) <span class="required">*</span></label>
                        <input type="text" name="do_number" class="form-control-modern" required 
                               value="<?php echo isset($edit_purchase) ? htmlspecialchars($edit_purchase['do_number']) : ''; ?>"
                               placeholder="Enter DO number">
                    </div>
                    
                    <button type="submit" name="<?php echo isset($_GET['edit']) ? 'edit_purchase' : 'add_purchase'; ?>" class="btn-submit">
                        <i class="fas fa-save"></i> <?php echo isset($_GET['edit']) ? 'Update Purchase' : 'Record Purchase'; ?>
                    </button>
                    
                    <?php if(isset($_GET['edit'])): ?>
                        <a href="purchases.php" class="btn-cancel-full">
                            <i class="fas fa-times"></i> Cancel Edit
                        </a>
                    <?php endif; ?>
                </form>
            </div>
        </div>
        
        <!-- Purchase History Table -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-list"></i>
                    <h4>Purchase History</h4>
                </div>
                <div class="table-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="tableSearch" placeholder="Search..." class="search-input">
                </div>
            </div>
            <div class="table-card-body scrollable-table">
                <div class="table-responsive">
                    <table class="modern-table" id="purchaseTable">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>DO Number</th>
                                <th>Fuel Type</th>
                                <th>Tank</th>
                                <th>Supplier</th>
                                <th>Payment</th>
                                <th>Quantity (L)</th>
                                <th>Rate (Rs)</th>
                                <th>Total (Rs)</th>
                                <th>Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(mysqli_num_rows($result) > 0): ?>
                                <?php while($row = mysqli_fetch_assoc($result)): ?>
                                    <tr>
                                        <td data-label="ID"><?php echo $row['id']; ?></td>
                                        <td data-label="DO Number"><strong><?php echo htmlspecialchars($row['do_number']); ?></strong></td>
                                        <td data-label="Fuel Type"><?php echo htmlspecialchars($row['fuel_name']); ?></td>
                                        <td data-label="Tank"><?php echo htmlspecialchars($row['tank_name']); ?></td>
                                        <td data-label="Supplier"><?php echo htmlspecialchars($row['supplier_name']); ?></td>
                                        <td data-label="Payment">
                                            <span class="payment-badge <?php echo $row['payment_method']; ?>">
                                                <?php echo ucfirst($row['payment_method']); ?>
                                            </span>
                                        </div>
                                        <td data-label="Quantity"><?php echo number_format($row['quantity'], 2); ?> L</div>
                                        <td data-label="Rate">Rs <?php echo number_format($row['rate'], 2); ?></div>
                                        <td data-label="Total" class="total-amount-cell">Rs <?php echo number_format($row['total_amount'], 2); ?></div>
                                        <td data-label="Date"><?php echo date('d-m-Y', strtotime($row['date_time'])); ?></div>
                                        <td data-label="Actions">
                                            <div class="action-buttons">
                                                <a href="?edit=<?php echo $row['id']; ?>" class="btn-action btn-edit" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <a href="?delete=<?php echo $row['id']; ?>" class="btn-action btn-delete" onclick="return confirm('Delete this purchase? This will reverse stock and balances!')" title="Delete">
                                                    <i class="fas fa-trash"></i>
                                                </a>
                                            </div>
                                        </div>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="11" class="empty-state">
                                        <i class="fas fa-database"></i>
                                        <p>No purchase records found</p>
                                        <small>Click "Record New Purchase" to get started</small>
                                    </div>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* Purchase Management 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;
}

h1, h2, h3, h4, h5, h6,
.page-header h2,
.stat-info h3,
.form-card-header h4,
.header-info h4,
.modern-table th {
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}

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

.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: 18px 24px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
    color: #fff;
    width: 100%;
}

.page-header h2 {
    font-size: 22px;
    margin-bottom: 4px;
}

.page-header p {
    font-size: 12px;
    opacity: 0.92;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}

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

/* Statistics Cards */
.stats-row {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    margin-bottom: 20px;
    width: 100%;
}

.stat-card {
    background: #fff;
    border-radius: 16px;
    padding: 16px 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    border: 1px solid #eef2f6;
    transition: all 0.3s;
}

.stat-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 20px rgba(160,70,87,0.1);
}

.stat-icon {
    width: 52px;
    height: 52px;
    background: rgba(160,70,87,0.1);
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.stat-icon i {
    font-size: 24px;
    color: #A04657;
}

.stat-info h3 {
    font-size: 24px;
    margin: 0;
    font-weight: 700;
    color: #1a2a3a;
}

.stat-info p {
    margin: 3px 0 0;
    font-weight: 500;
    color: #64748b;
    font-size: 11px;
}

.stat-trend {
    font-size: 10px;
    color: #94a3b8;
    display: block;
    margin-top: 3px;
}

/* Alerts */
.alert-custom {
    padding: 12px 20px;
    border-radius: 14px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 13px;
    font-weight: 500;
    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: 22px;
    cursor: pointer;
    opacity: 0.5;
}

/* Content Grid */
.content-grid {
    display: grid;
    grid-template-columns: 400px 1fr;
    gap: 20px;
    width: 100%;
}

/* Form Card */
.form-card {
    background: #fff;
    border-radius: 16px;
    border: 1px solid #eef2f6;
    overflow: hidden;
}

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

.form-card-header i {
    font-size: 18px;
}

.form-card-header h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

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

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

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

.required {
    color: #dc3545;
}

.form-control-modern {
    width: 100%;
    padding: 9px 12px;
    border: 2px solid #e2e8f0;
    border-radius: 10px;
    font-size: 13px;
    font-weight: 500;
    background: #fefefe;
    transition: all 0.2s;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
    box-shadow: 0 0 0 3px rgba(160,70,87,0.1);
}

.row-inputs {
    display: flex;
    gap: 12px;
    margin-bottom: 4px;
}

.input-half {
    flex: 1;
}

.info-box, .supplier-info-box {
    background: #f8fafc;
    border-radius: 10px;
    padding: 10px 14px;
    margin-bottom: 16px;
    border: 1px solid #eef2f6;
}

.info-title {
    font-weight: 700;
    color: #A04657;
    margin-bottom: 8px;
    font-size: 11px;
}

.info-row {
    display: flex;
    justify-content: space-between;
    padding: 5px 0;
    border-bottom: 1px solid rgba(0,0,0,0.05);
    font-size: 12px;
}

.info-row:last-child {
    border-bottom: none;
}

.info-row.highlight {
    background: #e8f5e9;
    margin: 5px -14px -5px -14px;
    padding: 8px 14px;
    border-radius: 8px;
}

.text-success {
    color: #28a745;
}

.due-amount {
    color: #dc3545;
}

.balance-amount {
    color: #6c5ce7;
}

.total-amount {
    background: #d4edda;
    color: #155724;
    font-size: 14px;
    font-weight: 700;
}

.btn-submit {
    width: 100%;
    padding: 10px;
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    color: #fff;
    border: none;
    border-radius: 10px;
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
    transition: all 0.2s;
}

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

.btn-cancel-full {
    display: block;
    text-align: center;
    margin-top: 10px;
    padding: 8px;
    background: #f1f5f9;
    color: #475569;
    text-decoration: none;
    border-radius: 10px;
    font-weight: 600;
    font-size: 12px;
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 16px;
    border: 1px solid #eef2f6;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    max-height: 65vh;
    width: 100%;
}

.table-card-header {
    padding: 12px 20px;
    border-bottom: 1px solid #eef2f6;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 10px;
    background: #fff;
    flex-shrink: 0;
}

.header-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.header-info i {
    font-size: 18px;
    color: #A04657;
}

.header-info h4 {
    margin: 0;
    font-size: 15px;
    font-weight: 600;
}

.table-search {
    position: relative;
}

.table-search i {
    position: absolute;
    left: 10px;
    top: 50%;
    transform: translateY(-50%);
    color: #94a3b8;
    font-size: 11px;
}

.search-input {
    padding: 7px 10px 7px 32px;
    border: 2px solid #e2e8f0;
    border-radius: 30px;
    width: 200px;
    font-size: 11px;
}

.search-input:focus {
    border-color: #A04657;
    outline: none;
}

.table-card-body.scrollable-table {
    overflow-y: auto;
    flex: 1;
}

.table-responsive {
    overflow-x: auto;
    width: 100%;
}

/* Modern Table */
.modern-table {
    width: 100%;
    border-collapse: collapse;
    min-width: 900px;
    font-size: 12px;
}

.modern-table th {
    padding: 10px 12px;
    background: #f8fafc;
    font-weight: 600;
    color: #475569;
    font-size: 11px;
    border-bottom: 2px solid #eef2f6;
    text-align: left;
    position: sticky;
    top: 0;
    z-index: 10;
}

.modern-table td {
    padding: 9px 12px;
    border-bottom: 1px solid #f0f4f9;
    font-size: 12px;
    font-weight: 500;
    color: #1e293b;
    vertical-align: middle;
}

.modern-table tr:hover td {
    background: #fefaf8;
}

.payment-badge {
    display: inline-block;
    padding: 3px 10px;
    border-radius: 30px;
    font-size: 10px;
    font-weight: 600;
}

.payment-badge.credit {
    background: #fff3cd;
    color: #856404;
}

.payment-badge.cash {
    background: #d4edda;
    color: #155724;
}

.payment-badge.bank {
    background: #e3f2fd;
    color: #1565c0;
}

.total-amount-cell {
    font-weight: 700;
    color: #A04657;
}

.action-buttons {
    display: flex;
    gap: 6px;
}

.btn-action {
    width: 28px;
    height: 28px;
    border-radius: 6px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    text-decoration: none;
    transition: all 0.2s;
    border: none;
    cursor: pointer;
}

.btn-edit {
    background: #fff3e0;
    color: #f39c12;
}

.btn-edit:hover {
    background: #f39c12;
    color: #fff;
    transform: scale(1.05);
}

.btn-delete {
    background: #ffebee;
    color: #dc3545;
}

.btn-delete:hover {
    background: #dc3545;
    color: #fff;
    transform: scale(1.05);
}

.empty-state {
    text-align: center;
    padding: 40px 20px !important;
}

.empty-state i {
    font-size: 48px;
    color: #A04657;
    opacity: 0.35;
    margin-bottom: 10px;
    display: block;
}

.empty-state p {
    font-size: 13px;
    font-weight: 600;
    color: #475569;
    margin-bottom: 4px;
}

.empty-state small {
    font-size: 11px;
    color: #94a3b8;
}

/* Scrollbar */
.table-card-body.scrollable-table::-webkit-scrollbar {
    width: 5px;
}

.table-card-body.scrollable-table::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}

.table-card-body.scrollable-table::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 10px;
}

::-webkit-scrollbar {
    width: 5px;
    height: 5px;
}

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

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

::-webkit-scrollbar-thumb:hover {
    background: #6b2a36;
}

/* Responsive */
@media (max-width: 1200px) {
    .stats-row {
        grid-template-columns: repeat(2, 1fr);
    }
    .content-grid {
        grid-template-columns: 1fr;
    }
}

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

@media (max-width: 768px) {
    .main-content {
        padding: 10px;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .stats-row {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .row-inputs {
        flex-direction: column;
        gap: 0;
    }
    .table-card-header {
        flex-direction: column;
        align-items: stretch;
    }
    .search-input {
        width: 100%;
    }
    .form-card-body {
        padding: 16px;
    }
    .stat-card {
        padding: 12px 16px;
    }
    .stat-icon {
        width: 44px;
        height: 44px;
    }
    .stat-icon i {
        font-size: 20px;
    }
    .stat-info h3 {
        font-size: 20px;
    }
}
</style>

<script>
// Update stock info based on selected tank
function updateStockInfo() {
    let tankSelect = document.getElementById('tank_id');
    let selectedOption = tankSelect.options[tankSelect.selectedIndex];
    let currentStock = selectedOption.getAttribute('data-current-stock');
    let quantity = parseFloat(document.getElementById('quantity').value) || 0;
    
    if(currentStock !== null) {
        let newStock = parseFloat(currentStock) + quantity;
        document.getElementById('displayCurrentStock').innerHTML = parseFloat(currentStock).toFixed(2) + ' Liters';
        document.getElementById('displayNewStock').innerHTML = newStock.toFixed(2) + ' Liters';
    }
}

// Update supplier balance display
function updateSupplierBalance() {
    let supplierSelect = document.getElementById('supplier_id');
    let selectedOption = supplierSelect.options[supplierSelect.selectedIndex];
    let balance = selectedOption.getAttribute('data-supplier-balance') || 0;
    document.getElementById('displaySupplierBalance').innerHTML = 'Rs ' + parseFloat(balance).toFixed(2);
    calculateNewSupplierBalance();
}

// Update payment method display
function updatePaymentMethod() {
    let paymentMethod = document.getElementById('payment_method').value;
    let newBalanceRow = document.getElementById('newBalanceRow');
    let bankDiv = document.getElementById('bank_account_div');
    let bankInfoBox = document.getElementById('bankInfoBox');
    
    if(paymentMethod === 'credit') {
        newBalanceRow.style.display = 'flex';
        bankDiv.style.display = 'none';
        bankInfoBox.style.display = 'none';
        calculateNewSupplierBalance();
    } else if(paymentMethod === 'bank') {
        newBalanceRow.style.display = 'none';
        bankDiv.style.display = 'block';
        bankInfoBox.style.display = 'block';
        document.getElementById('bank_id').setAttribute('required', 'required');
        updateBankInfo();
    } else {
        newBalanceRow.style.display = 'none';
        bankDiv.style.display = 'none';
        bankInfoBox.style.display = 'none';
        document.getElementById('bank_id').removeAttribute('required');
    }
}

// Update bank information
function updateBankInfo() {
    let bankSelect = document.getElementById('bank_id');
    let selectedOption = bankSelect.options[bankSelect.selectedIndex];
    let bankBalance = selectedOption.getAttribute('data-bank-balance') || 0;
    let totalAmount = parseFloat(document.getElementById('total_amount_hidden').value) || 0;
    
    document.getElementById('displayBankBalance').innerHTML = 'Rs ' + parseFloat(bankBalance).toFixed(2);
    
    let bankNewBalanceRow = document.getElementById('bankNewBalanceRow');
    let displayNewBankBalance = document.getElementById('displayNewBankBalance');
    
    if(totalAmount > 0) {
        bankNewBalanceRow.style.display = 'flex';
        let newBankBalance = parseFloat(bankBalance) - totalAmount;
        displayNewBankBalance.innerHTML = 'Rs ' + newBankBalance.toFixed(2);
        
        if(totalAmount > bankBalance) {
            displayNewBankBalance.style.color = '#dc3545';
            displayNewBankBalance.innerHTML += ' (Insufficient!)';
        } else {
            displayNewBankBalance.style.color = '#28a745';
        }
    } else {
        bankNewBalanceRow.style.display = 'none';
    }
}

// Calculate new supplier balance
function calculateNewSupplierBalance() {
    let supplierSelect = document.getElementById('supplier_id');
    let selectedOption = supplierSelect.options[supplierSelect.selectedIndex];
    let currentBalance = parseFloat(selectedOption.getAttribute('data-supplier-balance')) || 0;
    let totalAmount = parseFloat(document.getElementById('total_amount_hidden').value) || 0;
    let newBalance = currentBalance + totalAmount;
    document.getElementById('displayNewSupplierBalance').innerHTML = 'Rs ' + newBalance.toFixed(2);
}

// Calculate total amount
function calculateTotal() {
    var quantity = parseFloat(document.getElementById('quantity').value) || 0;
    var rate = parseFloat(document.getElementById('rate').value) || 0;
    var total = quantity * rate;
    document.getElementById('total_amount_display').value = 'Rs ' + total.toFixed(2);
    document.getElementById('total_amount_hidden').value = total.toFixed(2);
    updateStockInfo();
    calculateNewSupplierBalance();
    
    if(document.getElementById('payment_method').value === 'bank') {
        updateBankInfo();
    }
}

// Table search
document.getElementById('tableSearch')?.addEventListener('keyup', function() {
    let searchValue = this.value.toLowerCase().trim();
    let rows = document.querySelectorAll('#purchaseTable tbody tr');
    
    rows.forEach(row => {
        if (row.querySelector('.empty-state')) return;
        let text = row.textContent.toLowerCase();
        row.style.display = text.includes(searchValue) ? '' : 'none';
    });
});

// Initialize
document.addEventListener('DOMContentLoaded', function() {
    if(document.getElementById('tank_id')?.value) updateStockInfo();
    if(document.getElementById('supplier_id')?.value) updateSupplierBalance();
    if(document.getElementById('payment_method')?.value) updatePaymentMethod();
    calculateTotal();
});

// Auto hide alerts
document.querySelectorAll('.alert-custom').forEach(alert => {
    setTimeout(() => {
        if (alert) alert.style.opacity = '0';
        setTimeout(() => {
            if (alert) alert.remove();
        }, 300);
    }, 5000);
});
</script>

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