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

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

$success_message = "";
$error_message = "";
$selected_customer_id = isset($_GET['customer_id']) ? $_GET['customer_id'] : '';

// Get all customers
$customers_sql = "SELECT * FROM customers ORDER BY name";
$customers_result = mysqli_query($conn, $customers_sql);

// Get fuel types for dropdown
$fuel_types_sql = "SELECT id, name, sale_price FROM fuel_types ORDER BY name";
$fuel_types_result = mysqli_query($conn, $fuel_types_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);

// Get open shifts
$shifts_sql = "SELECT * FROM shift_entries WHERE status='OPEN' ORDER BY id DESC";
$shifts_result = mysqli_query($conn, $shifts_sql);

// Cart for credit sale items
$credit_cart = isset($_SESSION['credit_sale_cart']) ? $_SESSION['credit_sale_cart'] : [];

// Add item to credit cart
if(isset($_POST['add_to_cart'])) {
    $fuel_type_id = mysqli_real_escape_string($conn, $_POST['fuel_type_id']);
    $liters = mysqli_real_escape_string($conn, $_POST['liters']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    
    if($fuel_type_id && ($liters > 0 || $amount > 0)) {
        $fuel_sql = "SELECT id, name, sale_price FROM fuel_types WHERE id = $fuel_type_id";
        $fuel_result = mysqli_query($conn, $fuel_sql);
        $fuel = mysqli_fetch_assoc($fuel_result);
        $sale_price = $fuel['sale_price'];
        
        // Calculate based on what user provided
        if($liters > 0 && $amount == 0) {
            // Liters provided, calculate amount
            $amount = $liters * $sale_price;
        } elseif($amount > 0 && $liters == 0) {
            // Amount provided, calculate liters
            $liters = $amount / $sale_price;
        } elseif($liters > 0 && $amount > 0) {
            // Both provided, verify consistency or use amount to calculate liters
            $calculated_amount = $liters * $sale_price;
            if(abs($calculated_amount - $amount) > 0.01) {
                // If mismatch, use amount to calculate liters (amount is more reliable)
                $liters = $amount / $sale_price;
            }
        }
        
        $credit_cart[] = [
            'fuel_type_id' => $fuel_type_id,
            'fuel_name' => $fuel['name'],
            'sale_price' => $sale_price,
            'liters' => $liters,
            'amount' => $amount
        ];
        $_SESSION['credit_sale_cart'] = $credit_cart;
        $success_message = "Item added to cart!";
        header("Location: credit_sales.php");
        exit();
    } else {
        $error_message = "Please enter either Liters or Amount!";
    }
}

// Remove from cart
if(isset($_GET['remove_cart_item'])) {
    $index = intval($_GET['remove_cart_item']);
    if(isset($credit_cart[$index])) {
        unset($credit_cart[$index]);
        $_SESSION['credit_sale_cart'] = array_values($credit_cart);
        $success_message = "Item removed from cart!";
        header("Location: credit_sales.php");
        exit();
    }
}

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

// Calculate cart totals
$cart_subtotal = 0;
$cart_total_liters = 0;
foreach($credit_cart as $item) {
    $cart_subtotal += $item['amount'];
    $cart_total_liters += $item['liters'];
}

// Add Credit Sale with multiple items and cash advance
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_credit_sale'])) {
    $customer_id = mysqli_real_escape_string($conn, $_POST['customer_id']);
    $shift_id = mysqli_real_escape_string($conn, $_POST['shift_id']);
    $cash_advance = isset($_POST['cash_advance']) ? mysqli_real_escape_string($conn, $_POST['cash_advance']) : 0;
    $cash_advance_note = isset($_POST['cash_advance_note']) ? mysqli_real_escape_string($conn, $_POST['cash_advance_note']) : '';
    $date_time = date('Y-m-d H:i:s');
    
    if(empty($customer_id) || empty($shift_id) || empty($credit_cart)) {
        $error_message = "Please select customer, shift and add at least one fuel item!";
    } else {
        mysqli_begin_transaction($conn);
        
        try {
            $cust_sql = "SELECT balance, advance_balance FROM customers WHERE id = $customer_id";
            $cust_result = mysqli_query($conn, $cust_sql);
            $customer = mysqli_fetch_assoc($cust_result);
            
            // Total amount to add to customer balance = Fuel Sale + Cash Advance
            $net_payable = $cart_subtotal + $cash_advance;
            
            foreach($credit_cart as $item) {
                $fuel_type_id = $item['fuel_type_id'];
                $liters = $item['liters'];
                $amount = $item['amount'];
                
                $sql = "INSERT INTO credit_sales (customer_id, shift_id, fuel_type_id, amount, advance_used, liters, date_time) 
                        VALUES ('$customer_id', '$shift_id', '$fuel_type_id', '$amount', '0', '$liters', '$date_time')";
                mysqli_query($conn, $sql);
                
                $tank_sql = "SELECT id, current_stock FROM tanks WHERE fuel_type_id = $fuel_type_id AND current_stock >= $liters LIMIT 1";
                $tank_result = mysqli_query($conn, $tank_sql);
                
                if(mysqli_num_rows($tank_result) > 0) {
                    $tank = mysqli_fetch_assoc($tank_result);
                    $tank_id = $tank['id'];
                    $new_stock = $tank['current_stock'] - $liters;
                    
                    $update_tank = "UPDATE tanks SET current_stock = $new_stock, total_sale = total_sale + $liters WHERE id = $tank_id";
                    mysqli_query($conn, $update_tank);
                    
                    $movement_sql = "INSERT INTO stock_movements (product_id, movement_type, reference_no, quantity_in, quantity_out, balance_stock, date_time, user_name) 
                                    VALUES ($tank_id, 'sale', 'CS-$customer_id', 0, $liters, $new_stock, '$date_time', '{$_SESSION['username']}')";
                    mysqli_query($conn, $movement_sql);
                }
            }
            
            // Update customer balance
            if($net_payable > 0) {
                $update_balance = "UPDATE customers SET balance = balance + $net_payable WHERE id='$customer_id'";
                mysqli_query($conn, $update_balance);
            }
            
            // Record credit sale in customer_payments
            $payment_sql = "INSERT INTO customer_payments (customer_id, amount, payment_type, transaction_type, notes, date_time) 
                            VALUES ('$customer_id', '$net_payable', 'credit_sale', 'credit_sale', 'Credit Sale - Fuel Amount Rs $cart_subtotal, Cash Advance Rs $cash_advance, Total Rs $net_payable', '$date_time')";
            mysqli_query($conn, $payment_sql);
            
            // Record cash advance as a separate entry if cash_advance > 0
            if($cash_advance > 0) {
                $cash_advance_sql = "INSERT INTO customer_payments (customer_id, amount, payment_method, payment_type, transaction_type, notes, date_time) 
                                    VALUES ('$customer_id', '$cash_advance', 'cash', 'cash_advance', 'cash_advance', 'Cash Advance given - $cash_advance_note', '$date_time')";
                mysqli_query($conn, $cash_advance_sql);
            }
            
            mysqli_commit($conn);
            $_SESSION['credit_sale_cart'] = [];
            
            $success_message = "Transaction completed successfully! " . 
                              ($cash_advance > 0 ? "Cash Advance Rs " . number_format($cash_advance, 2) . " given. " : "") . 
                              "Total Added to Balance: Rs " . number_format($net_payable, 2);
            
            header("Location: credit_sales_report.php?success=1");
            exit();
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// Get all credit sales with fuel type
$sql = "SELECT cs.*, c.name as customer_name, c.vehicle_no, c.balance, c.advance_balance, s.shift_name, ft.name as fuel_name 
        FROM credit_sales cs
        LEFT JOIN customers c ON cs.customer_id = c.id
        LEFT JOIN shift_entries s ON cs.shift_id = s.id
        LEFT JOIN fuel_types ft ON cs.fuel_type_id = ft.id
        ORDER BY cs.id DESC
        LIMIT 10";
$result = mysqli_query($conn, $sql);

$total_credit_sales = mysqli_num_rows($result);
$total_amount = 0;
$total_liters = 0;
$total_advance_used = 0;

while($row = mysqli_fetch_assoc($result)) {
    $total_amount += $row['amount'];
    $total_liters += $row['liters'];
    $total_advance_used += $row['advance_used'];
}
mysqli_data_seek($result, 0);
?>

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

<div class="credit-sales-container">
    <!-- Page Header -->
    <div class="page-header">
        <div>
            <h2><i class="fas fa-shopping-cart"></i> Credit Sales Management</h2>
            <p>Record fuel credit sales - Enter liters OR amount, rate will auto-calculate</p>
        </div>
        <div class="header-actions">
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span><?php echo $total_credit_sales; ?> Recent Sales</span>
            </div>
            <a href="credit_sales_report.php" class="btn-report">
                <i class="fas fa-file-alt"></i> View Full Report
            </a>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-chart-line"></i></div>
            <div class="stat-info">
                <div class="stat-value"><?php echo $total_credit_sales; ?></div>
                <div class="stat-label">Recent Transactions</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-tachometer-alt"></i></div>
            <div class="stat-info">
                <div class="stat-value"><?php echo number_format($total_liters, 2); ?> L</div>
                <div class="stat-label">Total Liters</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-rupee-sign"></i></div>
            <div class="stat-info">
                <div class="stat-value">Rs <?php echo number_format($total_amount, 2); ?></div>
                <div class="stat-label">Total Amount</div>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon"><i class="fas fa-hand-holding-usd"></i></div>
            <div class="stat-info">
                <div class="stat-value">Rs 0.00</div>
                <div class="stat-label">Advance Used</div>
            </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="two-columns">
        <!-- Credit Sale Form -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fas fa-plus-circle"></i>
                <h4>Add Credit Sale</h4>
            </div>
            <div class="form-card-body">
                <div class="form-row">
                    <div class="form-group">
                        <label><i class="fas fa-user"></i> Select Customer <span class="required">*</span></label>
                        <select name="customer_id" id="customer_id" class="form-control" required onchange="updateCustomerDetails()">
                            <option value="">-- Select Customer --</option>
                            <?php 
                            mysqli_data_seek($customers_result, 0);
                            while($customer = mysqli_fetch_assoc($customers_result)): 
                                $selected = ($selected_customer_id == $customer['id']) ? 'selected' : '';
                            ?>
                                <option value="<?php echo $customer['id']; ?>" 
                                        data-balance="<?php echo $customer['balance']; ?>"
                                        data-vehicle="<?php echo htmlspecialchars($customer['vehicle_no']); ?>"
                                        data-name="<?php echo htmlspecialchars($customer['name']); ?>"
                                        <?php echo $selected; ?>>
                                    <?php echo htmlspecialchars($customer['name']); ?> - <?php echo htmlspecialchars($customer['vehicle_no']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="customer-info-box" id="customerInfoBox">
                        <div class="info-item">
                            <span class="info-label">Customer:</span>
                            <strong id="displayCustomer">-</strong>
                        </div>
                        <div class="info-item">
                            <span class="info-label">Vehicle:</span>
                            <strong id="displayVehicle">-</strong>
                        </div>
                        <div class="info-item">
                            <span class="info-label">Current Balance:</span>
                            <strong id="displayBalance">Rs 0.00</strong>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label><i class="fas fa-door-open"></i> Shift <span class="required">*</span></label>
                        <select name="shift_id" id="shift_id" class="form-control" required>
                            <option value="">-- Select Open Shift --</option>
                            <?php 
                            mysqli_data_seek($shifts_result, 0);
                            while($shift = mysqli_fetch_assoc($shifts_result)): 
                            ?>
                                <option value="<?php echo $shift['id']; ?>">
                                    <?php echo $shift['shift_name']; ?> Shift - <?php echo date('d-m-Y H:i', strtotime($shift['date_time'])); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                </div>
                
                <!-- Add Products Section -->
                <div class="add-products-section">
                    <h5><i class="fas fa-plus-circle"></i> Add Fuel Products</h5>
                    <div class="add-product-row">
                        <div class="add-product-field">
                            <label>Fuel Type</label>
                            <select id="cart_fuel_type" class="form-control" onchange="updateRateDisplay()">
                                <option value="">-- Select Fuel --</option>
                                <?php 
                                mysqli_data_seek($fuel_types_result, 0);
                                while($fuel = mysqli_fetch_assoc($fuel_types_result)): 
                                ?>
                                    <option value="<?php echo $fuel['id']; ?>" data-price="<?php echo $fuel['sale_price']; ?>">
                                        <?php echo $fuel['name']; ?> (Rs <?php echo number_format($fuel['sale_price'], 2); ?>/L)
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="add-product-field">
                            <label>Rate (Rs/L)</label>
                            <input type="text" id="cart_rate" class="form-control" readonly style="background:#f5f5f5;">
                        </div>
                    </div>
                    <div class="add-product-row" style="margin-top: 10px;">
                        <div class="add-product-field">
                            <label>Liters</label>
                            <input type="number" step="0.001" id="cart_liters" class="form-control" placeholder="0.000" onkeyup="calculateAmountFromLiters()">
                        </div>
                        <div class="add-product-field">
                            <label>Amount (Rs)</label>
                            <input type="number" step="0.01" id="cart_amount" class="form-control" placeholder="0.00" onkeyup="calculateLitersFromAmount()">
                        </div>
                        <div class="add-product-field add-btn-field">
                            <label>&nbsp;</label>
                            <button type="button" class="btn-add" onclick="addToCart()">
                                <i class="fas fa-cart-plus"></i> Add
                            </button>
                        </div>
                    </div>
                    <div class="info-text" style="margin-top: 8px; font-size: 11px; color: #666;">
                        <i class="fas fa-info-circle"></i> Enter either <strong>Liters</strong> or <strong>Amount</strong>, the other will auto-calculate
                    </div>
                </div>
                
                <!-- Cart Items -->
                <div class="cart-section" id="cartSection" style="display: <?php echo count($credit_cart) > 0 ? 'block' : 'none'; ?>">
                    <h5><i class="fas fa-shopping-cart"></i> Cart Items</h5>
                    <div class="cart-table-container">
                        <table class="cart-table">
                            <thead>
                                <tr>
                                    <th>Fuel Type</th>
                                    <th>Rate</th>
                                    <th>Liters</th>
                                    <th>Amount</th>
                                    <th></th>
                                </tr>
                            </thead>
                            <tbody id="cartItemsBody">
                                <?php foreach($credit_cart as $index => $item): ?>
                                    <tr>
                                        <td><strong><?php echo $item['fuel_name']; ?></strong></td>
                                        <td>Rs <?php echo number_format($item['sale_price'], 2); ?>/L</div>
                                        <td><?php echo number_format($item['liters'], 3); ?> L</div>
                                        <td>Rs <?php echo number_format($item['amount'], 2); ?></div>
                                        <td>
                                            <a href="?remove_cart_item=<?php echo $index; ?>" class="btn-remove" onclick="return confirm('Remove item?')">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                        </div>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                            <tfoot>
                                <tr class="cart-total">
                                    <td colspan="2"><strong>Total</strong></div>
                                    <td><strong><?php echo number_format($cart_total_liters, 3); ?> L</strong></div>
                                    <td><strong>Rs <?php echo number_format($cart_subtotal, 2); ?></strong></div>
                                    <td>
                                        <a href="?clear_cart=1" class="btn-clear" onclick="return confirm('Clear entire cart?')">
                                            <i class="fas fa-trash-alt"></i> Clear
                                        </a>
                                    </div>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
                
                <!-- Cash Advance Section - Give Cash to Customer -->
                <div class="cash-advance-section">
                    <div class="advance-header">
                        <i class="fas fa-money-bill-wave"></i> Cash Advance (Give Cash to Customer)
                    </div>
                    <div class="cash-advance-row">
                        <div class="cash-advance-field">
                            <label>Cash Advance Amount (Rs)</label>
                            <input type="number" step="0.01" id="cash_advance" class="form-control" value="0" onkeyup="updateNetPayable()">
                            <small>Amount to give as cash to customer (will be added to their balance)</small>
                        </div>
                        <div class="cash-advance-field">
                            <label>Note (Optional)</label>
                            <input type="text" id="cash_advance_note" class="form-control" placeholder="Reason for cash advance">
                        </div>
                    </div>
                </div>
                
                <!-- Transaction Preview -->
                <div class="preview-box">
                    <div class="preview-title">
                        <i class="fas fa-calculator"></i> Transaction Preview
                    </div>
                    <div class="preview-row">
                        <span>Fuel Subtotal:</span>
                        <strong>Rs <?php echo number_format($cart_subtotal, 2); ?></strong>
                    </div>
                    <div class="preview-row" id="cashAdvancePreviewRow">
                        <span>Cash Advance (Given):</span>
                        <strong id="cashAdvancePreview">Rs 0.00</strong>
                    </div>
                    <div class="preview-row highlight">
                        <span>Total Added to Customer Balance:</span>
                        <strong id="netPayablePreview">Rs <?php echo number_format($cart_subtotal, 2); ?></strong>
                    </div>
                    <div class="preview-row" style="border-top: 1px solid #ffc107; margin-top: 6px; padding-top: 6px;">
                        <span>Customer's New Balance:</span>
                        <strong id="newBalancePreview">Rs 0.00</strong>
                    </div>
                </div>
                
                <form method="POST" action="" id="creditSaleForm">
                    <input type="hidden" name="customer_id" id="form_customer_id" value="">
                    <input type="hidden" name="shift_id" id="form_shift_id" value="">
                    <input type="hidden" name="cash_advance" id="form_cash_advance" value="0">
                    <input type="hidden" name="cash_advance_note" id="form_cash_advance_note" value="">
                    <button type="submit" name="add_credit_sale" class="btn-submit" id="submitSaleBtn" <?php echo count($credit_cart) == 0 ? 'disabled' : ''; ?>>
                        <i class="fas fa-save"></i> Complete Transaction
                    </button>
                </form>
            </div>
        </div>
        
        <!-- Recent Credit Sales -->
        <div class="recent-sales-card">
            <div class="card-header-custom">
                <i class="fas fa-history"></i>
                <h4>Recent Credit Sales</h4>
            </div>
            <div class="card-body-custom">
                <?php if(mysqli_num_rows($result) > 0): ?>
                    <div class="recent-sales-list">
                        <?php while($row = mysqli_fetch_assoc($result)): ?>
                            <div class="sale-item">
                                <div class="sale-info">
                                    <div class="sale-customer">
                                        <i class="fas fa-user-circle"></i>
                                        <strong><?php echo htmlspecialchars($row['customer_name']); ?></strong>
                                    </div>
                                    <div class="sale-details">
                                        <span class="fuel-badge"><?php echo $row['fuel_name']; ?></span>
                                        <span class="liters"><?php echo number_format($row['liters'], 2); ?> L</span>
                                        <span class="amount">Rs <?php echo number_format($row['amount'], 2); ?></span>
                                    </div>
                                </div>
                                <div class="sale-meta">
                                    <span class="date"><?php echo date('d-m-Y', strtotime($row['date_time'])); ?></span>
                                    <span class="time"><?php echo date('h:i A', strtotime($row['date_time'])); ?></span>
                                </div>
                            </div>
                        <?php endwhile; ?>
                    </div>
                <?php else: ?>
                    <div class="empty-state">
                        <i class="fas fa-shopping-cart"></i>
                        <p>No credit sales found</p>
                        <small>Add items to cart and complete credit sale</small>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

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

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

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

h1, h2, h3, h4, h5, h6,
.page-header h2,
.stat-value,
.form-card-header h4,
.card-header-custom h4 {
    font-family: 'Times New Roman', serif;
}

.credit-sales-container {
    width: 100%;
    max-width: 100%;
    margin: 0;
    padding: 15px 20px;
}

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

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

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

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

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

.btn-report {
    background: rgba(255,255,255,0.2);
    color: #fff;
    padding: 6px 15px;
    border-radius: 30px;
    font-weight: 600;
    font-size: 12px;
    text-decoration: none;
    transition: all 0.2s;
}

.btn-report:hover {
    background: rgba(255,255,255,0.3);
    color: #fff;
}

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

.stat-card {
    background: #fff;
    border-radius: 14px;
    padding: 15px;
    display: flex;
    align-items: center;
    gap: 12px;
    box-shadow: 0 2px 6px rgba(0,0,0,0.06);
    border: 1px solid #e8e8e8;
}

.stat-icon {
    width: 45px;
    height: 45px;
    background: #fef0f2;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
}

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

.stat-value {
    font-size: 22px;
    font-weight: 800;
    color: #1a1a2e;
    line-height: 1.2;
}

.stat-label {
    font-size: 11px;
    color: #555;
    font-weight: 500;
    margin-top: 3px;
}

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

.alert-success {
    background: #d4edda;
    color: #155724;
    border-left: 4px solid #28a745;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border-left: 4px solid #dc3545;
}

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

/* Two Columns Layout */
.two-columns {
    display: grid;
    grid-template-columns: 1fr 0.95fr;
    gap: 20px;
    width: 100%;
}

/* Form Card */
.form-card {
    background: #fff;
    border-radius: 18px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.06);
    border: 1px solid #e8e8e8;
    height: fit-content;
}

.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;
    color: #fff;
}

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

.form-group {
    margin-bottom: 15px;
}

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

.form-group label i {
    color: #A04657;
    margin-right: 6px;
    width: 18px;
}

.required {
    color: #dc3545;
}

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

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

.form-row {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

/* Customer Info Box */
.customer-info-box {
    background: #f8f9fc;
    border-radius: 10px;
    padding: 12px;
    margin-bottom: 15px;
    border: 1px solid #e8e8e8;
}

.info-item {
    display: flex;
    justify-content: space-between;
    padding: 6px 0;
    border-bottom: 1px solid #e8e8e8;
}

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

.info-label {
    font-weight: 600;
    color: #555;
    font-size: 12px;
}

.info-item strong {
    color: #1a1a2e;
    font-size: 13px;
}

/* Add Products Section */
.add-products-section {
    background: #f8f9fc;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 18px;
}

.add-products-section h5 {
    margin-bottom: 12px;
    font-size: 13px;
    font-weight: 700;
    color: #333;
}

.add-product-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
    align-items: end;
}

.add-product-field label {
    font-size: 11px;
    font-weight: 600;
    margin-bottom: 4px;
    display: block;
    color: #555;
}

.add-btn-field {
    margin-bottom: 2px;
}

.btn-add {
    background: #28a745;
    color: #fff;
    border: none;
    padding: 9px 15px;
    border-radius: 10px;
    font-weight: 600;
    cursor: pointer;
    font-size: 12px;
    width: 100%;
}

.btn-add:hover {
    background: #1e7e34;
}

.info-text {
    background: #e3f2fd;
    padding: 8px 12px;
    border-radius: 8px;
}

/* Cart Section */
.cart-section {
    background: #f8f9fc;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 18px;
}

.cart-section h5 {
    margin-bottom: 12px;
    font-size: 13px;
    font-weight: 700;
    color: #333;
}

.cart-table-container {
    overflow-x: auto;
}

.cart-table {
    width: 100%;
    border-collapse: collapse;
}

.cart-table th {
    padding: 8px;
    background: #e9ecef;
    font-size: 11px;
    font-weight: 700;
    text-align: left;
    color: #333;
}

.cart-table td {
    padding: 8px;
    border-bottom: 1px solid #dee2e6;
    font-size: 12px;
    color: #444;
}

.cart-total {
    background: #e9ecef;
    font-weight: 700;
}

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

.btn-clear {
    color: #dc3545;
    text-decoration: none;
    font-size: 11px;
    margin-left: 8px;
}

/* Cash Advance Section */
.cash-advance-section {
    background: #fff8e1;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 18px;
    border-left: 4px solid #ff9800;
}

.cash-advance-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 12px;
    margin-top: 8px;
}

.cash-advance-field label {
    font-size: 11px;
    font-weight: 600;
    margin-bottom: 4px;
    display: block;
    color: #333;
}

.advance-header {
    font-weight: 700;
    color: #e65100;
    margin-bottom: 10px;
    font-size: 13px;
    display: flex;
    align-items: center;
    gap: 6px;
}

/* Preview Box */
.preview-box {
    background: #fff8e1;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 18px;
    border-left: 4px solid #ffc107;
}

.preview-title {
    font-weight: 700;
    color: #856404;
    margin-bottom: 10px;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 5px;
}

.preview-row {
    display: flex;
    justify-content: space-between;
    padding: 5px 0;
    font-size: 12px;
}

.preview-row.highlight {
    margin-top: 6px;
    padding-top: 6px;
    border-top: 1px dashed #ffc107;
    font-weight: 700;
}

.preview-row.highlight strong {
    color: #A04657;
    font-size: 14px;
}

/* Recent Sales Card */
.recent-sales-card {
    background: #fff;
    border-radius: 18px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.06);
    border: 1px solid #e8e8e8;
    height: fit-content;
}

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

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

.card-header-custom h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: #fff;
}

.card-body-custom {
    padding: 18px;
    max-height: 500px;
    overflow-y: auto;
}

.recent-sales-list {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.sale-item {
    background: #f8f9fc;
    border-radius: 10px;
    padding: 10px 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid #e8e8e8;
    transition: all 0.2s;
}

.sale-item:hover {
    border-color: #A04657;
    background: #fff;
}

.sale-customer {
    display: flex;
    align-items: center;
    gap: 6px;
    margin-bottom: 4px;
}

.sale-customer i {
    color: #A04657;
    font-size: 14px;
}

.sale-customer strong {
    font-size: 13px;
    color: #1a1a2e;
}

.sale-details {
    display: flex;
    gap: 8px;
    align-items: center;
    flex-wrap: wrap;
}

.fuel-badge {
    background: #e3f2fd;
    color: #1565c0;
    padding: 2px 8px;
    border-radius: 12px;
    font-size: 10px;
    font-weight: 600;
}

.liters {
    font-size: 11px;
    color: #17a2b8;
    font-weight: 600;
}

.amount {
    font-size: 12px;
    color: #dc3545;
    font-weight: 700;
}

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

.sale-meta .date {
    font-size: 10px;
    color: #666;
    display: block;
}

.sale-meta .time {
    font-size: 9px;
    color: #999;
}

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

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

.btn-submit:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.empty-state {
    text-align: center;
    padding: 30px;
}

.empty-state i {
    font-size: 40px;
    color: #A04657;
    opacity: 0.4;
    margin-bottom: 12px;
    display: block;
}

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

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

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

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

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

/* Responsive */
@media (max-width: 1100px) {
    .two-columns {
        grid-template-columns: 1fr;
        gap: 18px;
    }
    
    .stats-row {
        grid-template-columns: repeat(2, 1fr);
        gap: 12px;
    }
    
    .credit-sales-container {
        padding: 12px 15px;
    }
}

@media (max-width: 768px) {
    .credit-sales-container {
        padding: 10px;
    }
    
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 10px;
        padding: 15px;
    }
    
    .header-actions {
        justify-content: center;
    }
    
    .stats-row {
        grid-template-columns: 1fr;
    }
    
    .add-product-row {
        grid-template-columns: 1fr;
        gap: 10px;
    }
    
    .cash-advance-row {
        grid-template-columns: 1fr;
        gap: 10px;
    }
    
    .form-card-body {
        padding: 15px;
    }
    
    .sale-item {
        flex-direction: column;
        text-align: center;
        gap: 6px;
    }
    
    .sale-meta {
        text-align: center;
    }
    
    .sale-details {
        justify-content: center;
    }
}

/* Remove horizontal scroll */
body {
    overflow-x: hidden;
}

.container-fluid {
    padding-left: 0;
    padding-right: 0;
    overflow-x: hidden;
}
</style>

<script>
let currentBalance = 0;
let currentRate = 0;

function updateCustomerDetails() {
    let select = document.getElementById('customer_id');
    let selected = select.options[select.selectedIndex];
    let balance = parseFloat(selected.getAttribute('data-balance')) || 0;
    let vehicle = selected.getAttribute('data-vehicle') || '-';
    let name = selected.getAttribute('data-name') || '-';
    
    currentBalance = balance;
    
    document.getElementById('displayCustomer').innerHTML = name;
    document.getElementById('displayVehicle').innerHTML = vehicle;
    document.getElementById('displayBalance').innerHTML = 'Rs ' + balance.toFixed(2);
    
    document.getElementById('form_customer_id').value = select.value;
    
    let shiftSelect = document.getElementById('shift_id');
    document.getElementById('form_shift_id').value = shiftSelect.value;
    
    updateNetPayable();
}

function updateRateDisplay() {
    let fuelSelect = document.getElementById('cart_fuel_type');
    let selected = fuelSelect.options[fuelSelect.selectedIndex];
    let price = selected.getAttribute('data-price');
    
    if(price) {
        currentRate = parseFloat(price);
        document.getElementById('cart_rate').value = 'Rs ' + currentRate.toFixed(2) + '/L';
        document.getElementById('cart_rate').style.background = '#e8f5e9';
    } else {
        currentRate = 0;
        document.getElementById('cart_rate').value = '';
        document.getElementById('cart_rate').style.background = '#f5f5f5';
    }
    
    // Clear liters and amount when fuel changes
    document.getElementById('cart_liters').value = '';
    document.getElementById('cart_amount').value = '';
}

function calculateAmountFromLiters() {
    let liters = parseFloat(document.getElementById('cart_liters').value);
    if(currentRate > 0 && liters > 0) {
        let amount = liters * currentRate;
        document.getElementById('cart_amount').value = amount.toFixed(2);
    } else if(liters === 0 || isNaN(liters)) {
        document.getElementById('cart_amount').value = '';
    }
}

function calculateLitersFromAmount() {
    let amount = parseFloat(document.getElementById('cart_amount').value);
    if(currentRate > 0 && amount > 0) {
        let liters = amount / currentRate;
        document.getElementById('cart_liters').value = liters.toFixed(3);
    } else if(amount === 0 || isNaN(amount)) {
        document.getElementById('cart_liters').value = '';
    }
}

function addToCart() {
    let fuelSelect = document.getElementById('cart_fuel_type');
    let fuelId = fuelSelect.value;
    let liters = parseFloat(document.getElementById('cart_liters').value);
    let amount = parseFloat(document.getElementById('cart_amount').value);
    
    if(!fuelId) {
        alert('Please select fuel type');
        return;
    }
    
    if(!liters && !amount) {
        alert('Please enter either Liters or Amount');
        return;
    }
    
    if(currentRate <= 0) {
        alert('Invalid fuel rate');
        return;
    }
    
    // If only liters provided, amount will be calculated
    if(liters && !amount) {
        amount = liters * currentRate;
    }
    // If only amount provided, liters will be calculated
    else if(amount && !liters) {
        liters = amount / currentRate;
    }
    // If both provided, use amount to calculate liters (more accurate)
    else if(liters && amount) {
        // Recalculate liters from amount to maintain consistency
        liters = amount / currentRate;
    }
    
    let form = document.createElement('form');
    form.method = 'POST';
    form.action = '';
    form.style.display = 'none';
    let input1 = document.createElement('input');
    input1.type = 'hidden';
    input1.name = 'fuel_type_id';
    input1.value = fuelId;
    let input2 = document.createElement('input');
    input2.type = 'hidden';
    input2.name = 'liters';
    input2.value = liters.toFixed(3);
    let input3 = document.createElement('input');
    input3.type = 'hidden';
    input3.name = 'amount';
    input3.value = amount.toFixed(2);
    let input4 = document.createElement('input');
    input4.type = 'hidden';
    input4.name = 'add_to_cart';
    input4.value = '1';
    form.appendChild(input1);
    form.appendChild(input2);
    form.appendChild(input3);
    form.appendChild(input4);
    document.body.appendChild(form);
    form.submit();
}

function updateNetPayable() {
    let amount = <?php echo $cart_subtotal; ?>;
    let cashAdvance = parseFloat(document.getElementById('cash_advance').value) || 0;
    
    // Total added to customer balance = Fuel Amount + Cash Advance
    let totalAdded = amount + cashAdvance;
    let newBalance = currentBalance + totalAdded;
    
    document.getElementById('cashAdvancePreview').innerHTML = 'Rs ' + cashAdvance.toFixed(2);
    document.getElementById('netPayablePreview').innerHTML = 'Rs ' + totalAdded.toFixed(2);
    document.getElementById('newBalancePreview').innerHTML = 'Rs ' + newBalance.toFixed(2);
    
    document.getElementById('form_cash_advance').value = cashAdvance;
    document.getElementById('form_cash_advance_note').value = document.getElementById('cash_advance_note').value;
}

// Add event listeners
document.getElementById('cash_advance')?.addEventListener('input', updateNetPayable);
document.getElementById('cash_advance_note')?.addEventListener('input', function() {
    document.getElementById('form_cash_advance_note').value = this.value;
});

// Shift change handler
document.getElementById('shift_id').addEventListener('change', function() {
    document.getElementById('form_shift_id').value = this.value;
});

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

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