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

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

$success_message = "";
$error_message = "";
$customer_id = isset($_GET['customer_id']) ? (int)$_GET['customer_id'] : (isset($_POST['customer_id']) ? (int)$_POST['customer_id'] : 0);
$customer = null;

// Get customer details if ID exists
if($customer_id > 0) {
    $customer_sql = "SELECT * FROM customers WHERE id = '$customer_id'";
    $customer_result = mysqli_query($conn, $customer_sql);
    $customer = mysqli_fetch_assoc($customer_result);
}

// Get all customers for dropdown
$customers_sql = "SELECT id, name, phone, vehicle_no, balance, advance_balance FROM customers ORDER BY name";
$customers_result = mysqli_query($conn, $customers_sql);

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

// Add Advance Payment
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_advance'])) {
    $customer_id = mysqli_real_escape_string($conn, $_POST['customer_id']);
    $amount = mysqli_real_escape_string($conn, $_POST['amount']);
    $payment_method = mysqli_real_escape_string($conn, $_POST['payment_method']);
    $bank_id = isset($_POST['bank_id']) ? intval($_POST['bank_id']) : 0;
    $notes = mysqli_real_escape_string($conn, $_POST['notes']);
    $date_time = date('Y-m-d H:i:s');
    
    if(empty($customer_id)) {
        $error_message = "Please select a customer!";
    } elseif($amount <= 0) {
        $error_message = "Amount 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 advance payment record
            $sql = "INSERT INTO customer_payments (customer_id, amount, payment_method, notes, payment_type, date_time) 
                    VALUES ('$customer_id', '$amount', '$payment_method', '$notes', 'advance', '$date_time')";
            
            if(!mysqli_query($conn, $sql)) {
                throw new Exception("Failed to insert advance record: " . mysqli_error($conn));
            }
            
            // Update customer advance balance
            $update_customer = "UPDATE customers SET advance_balance = advance_balance + $amount WHERE id = '$customer_id'";
            if(!mysqli_query($conn, $update_customer)) {
                throw new Exception("Failed to update customer advance balance");
            }
            
            // For bank payment, add to bank account
            if($payment_method == 'bank' && $bank_id > 0) {
                // Update bank balance (add money to bank)
                $update_bank = "UPDATE bank_accounts SET balance = balance + $amount WHERE id = '$bank_id'";
                if(!mysqli_query($conn, $update_bank)) {
                    throw new Exception("Failed to update bank balance");
                }
                
                // Insert into bank book as deposit
                $bank_book_sql = "INSERT INTO bank_book (bank_id, entry_type, amount, description, reference_no, date_time) 
                                  VALUES ('$bank_id', 'Deposit', '$amount', 'Customer Advance - Customer ID: $customer_id', 'ADV-$customer_id', '$date_time')";
                if(!mysqli_query($conn, $bank_book_sql)) {
                    throw new Exception("Failed to record bank transaction");
                }
            }
            
            mysqli_commit($conn);
            $success_message = "Advance deposit of Rs " . number_format($amount, 2) . " recorded successfully!";
            
            // Refresh customer data
            $customer_sql = "SELECT * FROM customers WHERE id = '$customer_id'";
            $customer_result = mysqli_query($conn, $customer_sql);
            $customer = mysqli_fetch_assoc($customer_result);
            
        } catch (Exception $e) {
            mysqli_rollback($conn);
            $error_message = "Error: " . $e->getMessage();
        }
    }
}

// Get advance history for selected customer
$advance_history = null;
$total_advance = 0;
if($customer_id > 0 && $customer) {
    $history_sql = "SELECT * FROM customer_payments WHERE customer_id = '$customer_id' AND payment_type = 'advance' ORDER BY id DESC";
    $advance_history = mysqli_query($conn, $history_sql);
    
    while($row = mysqli_fetch_assoc($advance_history)) {
        $total_advance += $row['amount'];
    }
    mysqli_data_seek($advance_history, 0);
}
?>

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

<div class="advance-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-hand-holding-usd"></i> Customer Advance Deposit</h2>
            <p>Record advance payments from customers for future fuel purchases</p>
        </div>
        <div class="header-right">
            <a href="customers.php" class="btn-back"><i class="fas fa-arrow-left"></i> Back to Customers</a>
        </div>
    </div>

    <!-- Success/Error Messages -->
    <?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">
        <!-- Customer Selection & Advance Form -->
        <div class="form-card">
            <div class="form-card-header">
                <i class="fas fa-plus-circle"></i>
                <h4>Record Advance Deposit</h4>
            </div>
            <div class="form-card-body">
                <form method="POST" action="" id="advanceForm">
                    <div class="input-group-custom">
                        <label><i class="fas fa-user"></i> Select Customer <span class="required">*</span></label>
                        <select name="customer_id" id="customer_id" class="form-control-modern" required onchange="this.form.submit()">
                            <option value="">-- Select Customer --</option>
                            <?php 
                            mysqli_data_seek($customers_result, 0);
                            while($cust = mysqli_fetch_assoc($customers_result)): 
                                $selected = ($customer_id == $cust['id']) ? 'selected' : '';
                            ?>
                                <option value="<?php echo $cust['id']; ?>" 
                                        data-advance="<?php echo $cust['advance_balance']; ?>"
                                        data-phone="<?php echo htmlspecialchars($cust['phone'] ?? ''); ?>"
                                        data-vehicle="<?php echo htmlspecialchars($cust['vehicle_no'] ?? ''); ?>"
                                        data-name="<?php echo htmlspecialchars($cust['name']); ?>"
                                        <?php echo $selected; ?>>
                                    <?php echo htmlspecialchars($cust['name']); ?> 
                                    (Advance: Rs <?php echo number_format($cust['advance_balance'], 2); ?>)
                                </option>
                            <?php endwhile; ?>
                        </select>
                        <small class="input-help">Select customer who is making advance payment</small>
                    </div>
                    
                    <?php if($customer && $customer_id > 0): ?>
                        <!-- Customer Info Card -->
                        <div class="customer-info-card">
                            <div class="customer-avatar"><i class="fas fa-user-circle"></i></div>
                            <div class="customer-details">
                                <h4><?php echo htmlspecialchars($customer['name']); ?></h4>
                                <div class="info-grid">
                                    <div class="info-item"><i class="fas fa-phone"></i> <?php echo htmlspecialchars($customer['phone'] ?? 'N/A'); ?></div>
                                    <div class="info-item"><i class="fas fa-truck"></i> <?php echo htmlspecialchars($customer['vehicle_no'] ?? 'N/A'); ?></div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="balance-card">
                            <div class="balance-row">
                                <span><i class="fas fa-rupee-sign"></i> Current Receivable:</span>
                                <strong class="text-danger">Rs <?php echo number_format($customer['balance'] ?? 0, 2); ?></strong>
                            </div>
                            <div class="balance-row">
                                <span><i class="fas fa-hand-holding-usd"></i> Current Advance Balance:</span>
                                <strong class="text-info">Rs <?php echo number_format($customer['advance_balance'] ?? 0, 2); ?></strong>
                            </div>
                            <div class="balance-row">
                                <span><i class="fas fa-balance-scale"></i> Net Position:</span>
                                <strong class="<?php echo ($customer['balance'] - $customer['advance_balance']) > 0 ? 'text-danger' : (($customer['balance'] - $customer['advance_balance']) < 0 ? 'text-success' : ''); ?>">
                                    Rs <?php echo number_format(abs($customer['balance'] - $customer['advance_balance']), 2); ?>
                                    <?php echo ($customer['balance'] - $customer['advance_balance']) > 0 ? 'Dr' : (($customer['balance'] - $customer['advance_balance']) < 0 ? 'Cr' : ''); ?>
                                </strong>
                            </div>
                        </div>
                        
                        <div class="input-group-custom">
                            <label><i class="fas fa-money-bill-wave"></i> Payment Method <span class="required">*</span></label>
                            <select name="payment_method" id="payment_method" class="form-control-modern" required onchange="toggleBankField()">
                                <option value="cash">Cash</option>
                                <option value="bank">Bank Transfer</option>
                            </select>
                            <small class="input-help">Select payment method for this advance</small>
                        </div>
                        
                        <!-- Bank Account Selection (shown only when bank is selected) -->
                        <div class="input-group-custom" id="bank_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']; ?>"
                                            data-bank-name="<?php echo htmlspecialchars($bank['bank_name']); ?>">
                                        <?php echo htmlspecialchars($bank['bank_name']); ?> - 
                                        <?php echo htmlspecialchars($bank['account_title']); ?> 
                                        (Balance: Rs <?php echo number_format($bank['balance'], 2); ?>)
                                    </option>
                                <?php endwhile; ?>
                            </select>
                            <small class="input-help">Amount will be deposited to selected bank account</small>
                        </div>
                        
                        <!-- Bank Info Box (shown when bank is selected) -->
                        <div class="bank-info-box" id="bankInfoBox" style="display: none;">
                            <div class="info-row">
                                <span><i class="fas fa-university"></i> Bank Balance:</span>
                                <strong id="displayBankBalance">Rs 0.00</strong>
                            </div>
                            <div class="info-row" style="color: #28a745;">
                                <span><i class="fas fa-arrow-up"></i> After Deposit:</span>
                                <strong id="displayNewBankBalance">Rs 0.00</strong>
                            </div>
                        </div>
                        
                        <div class="input-group-custom">
                            <label><i class="fas fa-rupee-sign"></i> Advance Amount <span class="required">*</span></label>
                            <input type="number" step="0.01" name="amount" id="amount" class="form-control-modern" required placeholder="Enter advance amount" onkeyup="validateAmount()">
                            <small class="input-help">Amount customer is paying in advance</small>
                        </div>
                        
                        <div class="advance-preview" id="advancePreview" style="display: none;">
                            <div class="preview-row">
                                <span><i class="fas fa-info-circle"></i> Advance Amount:</span>
                                <strong id="previewAmount">Rs 0.00</strong>
                            </div>
                            <div class="preview-divider"></div>
                            <div class="preview-row">
                                <span><i class="fas fa-chart-line"></i> New Advance Balance:</span>
                                <strong id="previewNewAdvance" style="color: #17a2b8;">Rs 0.00</strong>
                            </div>
                            <div class="preview-row">
                                <span><i class="fas fa-balance-scale"></i> New Net Position:</span>
                                <strong id="previewNetPosition">Rs 0.00</strong>
                            </div>
                        </div>
                        
                        <div class="input-group-custom">
                            <label><i class="fas fa-sticky-note"></i> Notes (Optional)</label>
                            <textarea name="notes" class="form-control-modern" rows="2" placeholder="Reference or remarks for this advance payment"></textarea>
                        </div>
                        
                        <button type="submit" name="add_advance" class="btn-submit">
                            <i class="fas fa-save"></i> Record Advance Deposit
                        </button>
                    <?php elseif($customer_id == 0): ?>
                        <div class="no-customer-warning">
                            <i class="fas fa-info-circle"></i>
                            <p>Select a customer to record advance deposit</p>
                            <small>Please select a customer from the dropdown above</small>
                        </div>
                    <?php endif; ?>
                </form>
            </div>
        </div>
        
        <!-- Advance History Table -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-history"></i>
                    <h4>Advance Payment History</h4>
                </div>
                <?php if($customer): ?>
                    <div class="table-stats">
                        Total Advances: <strong>Rs <?php echo number_format($total_advance, 2); ?></strong>
                    </div>
                <?php endif; ?>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table" id="advanceTable">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Date & Time</th>
                                <th>Amount (Rs)</th>
                                <th>Payment Method</th>
                                <th>Notes</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($advance_history && mysqli_num_rows($advance_history) > 0): ?>
                                <?php $sn = 1; while($payment = mysqli_fetch_assoc($advance_history)): ?>
                                    <tr>
                                        <td data-label="#"><?php echo $sn++; ?></td>
                                        <td data-label="Date & Time"><?php echo date('d-m-Y H:i:s', strtotime($payment['date_time'])); ?></td>
                                        <td data-label="Amount" class="advance-amount">Rs <?php echo number_format($payment['amount'], 2); ?></td>
                                        <td data-label="Payment Method">
                                            <span class="method-badge <?php echo $payment['payment_method'] == 'bank' ? 'bank' : 'cash'; ?>">
                                                <i class="fas <?php echo $payment['payment_method'] == 'bank' ? 'fa-university' : 'fa-money-bill-wave'; ?>"></i>
                                                <?php echo ucfirst($payment['payment_method'] ?: 'cash'); ?>
                                            </span>
                                        </div>
                                        <td data-label="Notes"><?php echo htmlspecialchars($payment['notes'] ?: '—'); ?></td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="5" class="empty-state">
                                        <i class="fas fa-hand-holding-usd"></i>
                                        <p>No advance payments recorded yet</p>
                                        <?php if($customer): ?>
                                            <small>Record first advance payment for this customer</small>
                                        <?php else: ?>
                                            <small>Select a customer to view advance history</small>
                                        <?php endif; ?>
                                    </div>
                                    </tr>
                            <?php endif; ?>
                        </tbody>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

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

body {
    background: #f5f7fb;
}

/* Headings use Times New Roman */
h1, h2, h3, h4, h5, h6,
.page-header h2,
.form-card-header h4,
.header-info h4 {
    font-family: 'Times New Roman', serif;
}

.advance-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 20px;
}

/* Page Header */
.page-header {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    border-radius: 24px;
    padding: 28px 32px;
    margin-bottom: 32px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;
    box-shadow: 0 4px 20px rgba(160,70,87,0.2);
}

.page-header h2 {
    color: #fff;
    margin: 0 0 8px 0;
    font-size: 28px;
    font-weight: 700;
}

.page-header h2 i {
    margin-right: 12px;
}

.page-header p {
    color: rgba(255,255,255,0.9);
    margin: 0;
    font-size: 14px;
}

.btn-back {
    background: rgba(255,255,255,0.2);
    color: #fff;
    padding: 10px 22px;
    border-radius: 40px;
    text-decoration: none;
    font-weight: 600;
    font-size: 14px;
    display: inline-flex;
    align-items: center;
    gap: 10px;
    transition: all 0.3s;
}

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

/* Content Grid */
.content-grid {
    display: grid;
    grid-template-columns: 420px 1fr;
    gap: 28px;
}

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

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

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

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

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

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

.input-group-custom label {
    display: block;
    margin-bottom: 8px;
    font-weight: 600;
    color: #333;
    font-size: 14px;
}

.input-group-custom label i {
    color: #A04657;
    margin-right: 8px;
    width: 18px;
}

.required {
    color: #dc3545;
}

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

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

.input-help {
    display: block;
    font-size: 11px;
    color: #999;
    margin-top: 6px;
}

/* Customer Info Card */
.customer-info-card {
    background: #f8f9fc;
    border-radius: 16px;
    padding: 16px;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 16px;
    border: 1px solid #f0f0f0;
}

.customer-avatar i {
    font-size: 48px;
    color: #A04657;
}

.customer-details h4 {
    margin: 0 0 8px 0;
    font-size: 16px;
    font-weight: 700;
}

.info-grid {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
}

.info-item {
    font-size: 13px;
    color: #555;
    display: flex;
    align-items: center;
    gap: 6px;
}

.info-item i {
    color: #A04657;
}

/* Balance Card */
.balance-card {
    background: #f8f9fa;
    border-radius: 16px;
    padding: 16px 20px;
    margin-bottom: 20px;
    border-left: 4px solid #17a2b8;
}

.balance-row {
    display: flex;
    justify-content: space-between;
    padding: 8px 0;
    font-size: 14px;
}

.balance-row strong {
    font-size: 15px;
}

.text-danger { color: #dc3545 !important; }
.text-success { color: #28a745 !important; }
.text-info { color: #17a2b8 !important; }

/* Bank Info Box */
.bank-info-box {
    background: #e8f5e9;
    border-radius: 14px;
    padding: 12px 16px;
    margin-bottom: 20px;
    border-left: 4px solid #28a745;
}

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

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

/* Method Badge */
.method-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.method-badge.cash {
    background: #e8f5e9;
    color: #2e7d32;
}

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

/* Advance Preview */
.advance-preview {
    background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
    border-radius: 14px;
    padding: 14px;
    margin-bottom: 24px;
}

.preview-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 6px 0;
    font-size: 13px;
}

.preview-row strong {
    font-weight: 700;
}

.preview-divider {
    height: 1px;
    background: #90caf9;
    margin: 8px 0;
}

.btn-submit {
    width: 100%;
    padding: 14px;
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    color: #fff;
    border: none;
    border-radius: 14px;
    font-weight: 700;
    font-size: 15px;
    cursor: pointer;
    transition: all 0.3s;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 10px;
}

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

/* No Customer Warning */
.no-customer-warning {
    text-align: center;
    padding: 40px 20px;
    background: #f8f9fa;
    border-radius: 16px;
}

.no-customer-warning i {
    font-size: 48px;
    color: #A04657;
    margin-bottom: 16px;
    opacity: 0.5;
}

.no-customer-warning p {
    font-size: 16px;
    font-weight: 600;
    color: #555;
    margin-bottom: 8px;
}

.no-customer-warning small {
    font-size: 12px;
    color: #999;
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 24px;
    overflow: hidden;
    box-shadow: 0 2px 12px rgba(0,0,0,0.04);
    border: 1px solid #f0f0f0;
}

.table-card-header {
    padding: 20px 24px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

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

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

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

.table-stats {
    font-size: 14px;
    color: #666;
}

.table-stats strong {
    color: #A04657;
    font-size: 18px;
    margin-left: 8px;
}

/* Modern Table */
.modern-table {
    width: 100%;
    border-collapse: collapse;
}

.modern-table th {
    padding: 14px 20px;
    background: #fafbfc;
    font-weight: 700;
    color: #555;
    font-size: 12px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    border-bottom: 1px solid #e8e8e8;
}

.modern-table td {
    padding: 14px 20px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
    font-size: 13px;
    color: #444;
}

.modern-table tbody tr:hover {
    background: #fef8f9;
}

.advance-amount {
    color: #17a2b8;
    font-weight: 700;
}

/* Alert Styles */
.alert-custom {
    padding: 16px 24px;
    border-radius: 16px;
    margin-bottom: 24px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    animation: slideIn 0.3s ease;
    font-weight: 500;
}

@keyframes slideIn {
    from { transform: translateY(-20px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

.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: 24px;
    cursor: pointer;
    opacity: 0.5;
    transition: opacity 0.3s;
}

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

/* Empty State */
.empty-state {
    text-align: center;
    padding: 50px !important;
}

.empty-state i {
    font-size: 56px;
    color: #A04657;
    margin-bottom: 16px;
    opacity: 0.5;
    display: block;
}

.empty-state p {
    margin: 0;
    color: #666;
    font-weight: 500;
}

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

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

@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 16px;
    }
    
    .customer-info-card {
        flex-direction: column;
        text-align: center;
    }
    
    .info-grid {
        justify-content: center;
    }
    
    .modern-table th {
        display: none;
    }
    
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 50%;
        position: relative;
        border-bottom: none;
    }
    
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 20px;
        width: 45%;
        text-align: left;
        font-weight: 700;
        color: #555;
        font-size: 11px;
    }
    
    .modern-table tr {
        display: block;
        margin-bottom: 12px;
        border: 1px solid #e8e8e8;
        border-radius: 12px;
        overflow: hidden;
    }
}

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

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

::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 10px;
}
</style>

<script>
// Toggle bank field based on payment method
function toggleBankField() {
    const paymentMethod = document.getElementById('payment_method').value;
    const bankDiv = document.getElementById('bank_div');
    const bankInfoBox = document.getElementById('bankInfoBox');
    const isBank = (paymentMethod === 'bank');
    
    if(bankDiv) {
        bankDiv.style.display = isBank ? 'block' : 'none';
    }
    if(bankInfoBox) {
        bankInfoBox.style.display = isBank ? 'block' : 'none';
    }
    
    if(isBank) {
        document.getElementById('bank_id').setAttribute('required', 'required');
        updateBankInfo();
    } else {
        document.getElementById('bank_id').removeAttribute('required');
    }
}

// Update bank information
function updateBankInfo() {
    const bankSelect = document.getElementById('bank_id');
    if(!bankSelect) return;
    
    const selectedOption = bankSelect.options[bankSelect.selectedIndex];
    const bankBalance = parseFloat(selectedOption.getAttribute('data-bank-balance')) || 0;
    const amount = parseFloat(document.getElementById('amount').value) || 0;
    
    document.getElementById('displayBankBalance').innerHTML = 'Rs ' + bankBalance.toFixed(2);
    
    const newBalance = bankBalance + amount; // Add to bank for advance payments
    const newBalanceSpan = document.getElementById('displayNewBankBalance');
    newBalanceSpan.innerHTML = 'Rs ' + newBalance.toFixed(2);
    newBalanceSpan.style.color = '#28a745';
}

// Validate amount and show preview
function validateAmount() {
    const amount = parseFloat(document.getElementById('amount')?.value) || 0;
    const customerSelect = document.getElementById('customer_id');
    const selectedOption = customerSelect.options[customerSelect.selectedIndex];
    const currentAdvance = parseFloat(selectedOption.getAttribute('data-advance')) || 0;
    const previewDiv = document.getElementById('advancePreview');
    
    if(amount > 0 && previewDiv) {
        previewDiv.style.display = 'block';
        document.getElementById('previewAmount').innerHTML = 'Rs ' + amount.toFixed(2);
        const newAdvance = currentAdvance + amount;
        document.getElementById('previewNewAdvance').innerHTML = 'Rs ' + newAdvance.toFixed(2);
        
        // Get receivable from balance (assuming receivable is 0 for new customers)
        const newNet = (0 - newAdvance);
        document.getElementById('previewNetPosition').innerHTML = 'Rs ' + Math.abs(newNet).toFixed(2) + ' Cr';
        document.getElementById('previewNetPosition').style.color = '#28a745';
        
        // Update bank info if bank payment selected
        if(document.getElementById('payment_method').value === 'bank') {
            updateBankInfo();
        }
    } else if(previewDiv) {
        previewDiv.style.display = 'none';
    }
}

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

// Add event listeners
document.getElementById('amount')?.addEventListener('input', function() {
    if(document.getElementById('payment_method').value === 'bank') {
        updateBankInfo();
    }
});

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

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