<?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 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 Payment
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_payment'])) {
    $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;
    $description = mysqli_real_escape_string($conn, $_POST['description']);
    $date_time = date('Y-m-d H:i:s');
    
    if(empty($customer_id) || $amount <= 0) {
        $error_message = "Customer and valid amount are required!";
    } elseif($payment_method == 'bank' && empty($bank_id)) {
        $error_message = "Please select a bank account for bank payment!";
    } else {
        // Check if amount exceeds balance
        $balance_sql = "SELECT balance FROM customers WHERE id='$customer_id'";
        $balance_result = mysqli_query($conn, $balance_sql);
        $customer = mysqli_fetch_assoc($balance_result);
        
        if($amount > $customer['balance']) {
            $error_message = "Amount cannot exceed customer balance (Rs " . number_format($customer['balance'], 2) . ")";
        } else {
            mysqli_begin_transaction($conn);
            
            try {
                // Insert payment with description and payment method
                $sql = "INSERT INTO customer_payments (customer_id, amount, payment_method, notes, date_time) 
                        VALUES ('$customer_id', '$amount', '$payment_method', '$description', '$date_time')";
                mysqli_query($conn, $sql);
                
                // Update customer balance
                $update_balance = "UPDATE customers SET balance = balance - $amount WHERE id='$customer_id'";
                mysqli_query($conn, $update_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'";
                    mysqli_query($conn, $update_bank);
                    
                    // 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 Payment - Customer ID: $customer_id', 'CUST-PAY-$customer_id', '$date_time')";
                    mysqli_query($conn, $bank_book_sql);
                }
                
                mysqli_commit($conn);
                $success_message = "Payment received successfully!";
            } catch (Exception $e) {
                mysqli_rollback($conn);
                $error_message = "Error: " . $e->getMessage();
            }
        }
    }
}

// Get all payments
$sql = "SELECT cp.*, c.name as customer_name, c.vehicle_no, c.balance
        FROM customer_payments cp
        LEFT JOIN customers c ON cp.customer_id = c.id
        ORDER BY cp.id DESC";
$result = mysqli_query($conn, $sql);

// Get statistics
$total_payments = mysqli_num_rows($result);
$total_amount_received = 0;

while($row = mysqli_fetch_assoc($result)) {
    $total_amount_received += $row['amount'];
}
mysqli_data_seek($result, 0);
?>

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

<div class="receiving-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-hand-holding-usd"></i> Customer Payment Receiving</h2>
            <p>Record customer payments and manage outstanding balances</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span><?php echo $total_payments; ?> Total Transactions</span>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="row g-4 mb-4">
        <div class="col-md-4">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-hand-holding-usd"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo $total_payments; ?></h3>
                    <p>Total Payments</p>
                    <span class="stat-trend">Received</span>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <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_received, 2); ?></h3>
                    <p>Total Received</p>
                    <span class="stat-trend">Amount Collected</span>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-users"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo mysqli_num_rows($customers_result); ?></h3>
                    <p>Active Customers</p>
                    <span class="stat-trend">With Accounts</span>
                </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="row g-4">
        <!-- Payment Form -->
        <div class="col-xl-5 col-lg-6">
            <div class="form-card">
                <div class="form-card-header">
                    <i class="fas fa-plus-circle"></i>
                    <h4>Receive Payment</h4>
                </div>
                <div class="form-card-body">
                    <form method="POST" action="" id="paymentForm">
                        <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="updateBalance()">
                                <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-name="<?php echo htmlspecialchars($customer['name']); ?>"
                                            data-vehicle="<?php echo htmlspecialchars($customer['vehicle_no']); ?>"
                                            <?php echo $selected; ?>>
                                        <?php echo htmlspecialchars($customer['name']); ?> - <?php echo htmlspecialchars($customer['vehicle_no']); ?>
                                    </option>
                                <?php endwhile; ?>
                            </select>
                            <small class="input-help">Select customer making payment</small>
                        </div>
                        
                        <!-- Customer Info Card -->
                        <div class="customer-info-card" id="customerInfoCard" style="display: none;">
                            <div class="info-row">
                                <span><i class="fas fa-user"></i> Customer:</span>
                                <strong id="customerName">-</strong>
                            </div>
                            <div class="info-row">
                                <span><i class="fas fa-truck"></i> Vehicle:</span>
                                <strong id="customerVehicle">-</strong>
                            </div>
                            <div class="info-row">
                                <span><i class="fas fa-rupee-sign"></i> Current Balance:</span>
                                <strong id="currentBalance" style="color: #A04657;">Rs 0.00</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 how customer is paying</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> Payment Amount (Rs) <span class="required">*</span></label>
                            <input type="number" step="0.01" name="amount" id="amount" class="form-control-modern" required placeholder="Enter amount to receive" onkeyup="validateAmount()">
                            <small class="input-help">Enter the amount customer is paying</small>
                        </div>
                        
                        <!-- Description Field -->
                        <div class="input-group-custom">
                            <label><i class="fas fa-file-alt"></i> Description (Optional)</label>
                            <textarea name="description" id="description" class="form-control-modern" rows="3" placeholder="Enter payment description or notes (e.g., Cheque number, reference, partial payment note, etc.)" style="resize: vertical;"></textarea>
                            <small class="input-help">Add any additional information about this payment</small>
                        </div>
                        
                        <!-- Payment Preview -->
                        <div class="payment-preview" id="paymentPreview" style="display: none;">
                            <div class="preview-title">
                                <i class="fas fa-calculator"></i> Payment Preview
                            </div>
                            <div class="preview-row">
                                <span>Payment Amount:</span>
                                <strong id="previewAmount">Rs 0.00</strong>
                            </div>
                            <div class="preview-row">
                                <span>Current Balance:</span>
                                <strong id="previewCurrentBalance">Rs 0.00</strong>
                            </div>
                            <div class="preview-divider"></div>
                            <div class="preview-row">
                                <span>New Balance:</span>
                                <strong id="previewNewBalance">Rs 0.00</strong>
                            </div>
                        </div>
                        
                        <div class="remaining-box" id="remainingBox">
                            <div class="remaining-title">
                                <i class="fas fa-chart-line"></i> After Payment
                            </div>
                            <div class="remaining-amount" id="remainingAmount">
                               Rs 0.00
                            </div>
                            <div class="remaining-status" id="remainingStatus"></div>
                        </div>
                        
                        <button type="submit" name="add_payment" class="btn-submit">
                            <i class="fas fa-save"></i> Receive Payment
                        </button>
                    </form>
                </div>
            </div>
            
            <!-- Info Card -->
            <div class="info-card">
                <div class="info-card-header">
                    <i class="fas fa-info-circle"></i>
                    <h5>Payment Information</h5>
                </div>
                <div class="info-card-body">
                    <div class="info-item">
                        <span><i class="fas fa-hand-holding-usd"></i> Payment Type:</span>
                        <span>Credit Recovery</span>
                    </div>
                    <div class="info-item">
                        <span><i class="fas fa-chart-line"></i> Balance Update:</span>
                        <span>Automatically deducted</span>
                    </div>
                    <div class="info-item">
                        <span><i class="fas fa-shield-alt"></i> Validation:</span>
                        <span>Amount cannot exceed balance</span>
                    </div>
                    <div class="info-item">
                        <span><i class="fas fa-print"></i> Receipt:</span>
                        <span>Transaction recorded</span>
                    </div>
                    <div class="info-item">
                        <span><i class="fas fa-file-alt"></i> Description:</span>
                        <span>Optional notes field available</span>
                    </div>
                    <div class="info-item">
                        <span><i class="fas fa-university"></i> Bank Payment:</span>
                        <span>Auto-deposit to bank</span>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Payment History -->
        <div class="col-xl-7 col-lg-6">
            <div class="table-card">
                <div class="table-card-header">
                    <div class="header-info">
                        <i class="fas fa-history"></i>
                        <h4>Payment History</h4>
                    </div>
                    <div class="table-search">
                        <i class="fas fa-search"></i>
                        <input type="text" id="tableSearch" placeholder="Search by customer..." class="search-input">
                    </div>
                </div>
                <div class="table-card-body">
                    <div class="table-responsive">
                        <table class="modern-table" id="paymentsTable">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Customer</th>
                                    <th>Vehicle</th>
                                    <th>Amount Received (Rs)</th>
                                    <th>Payment Method</th>
                                    <th>Description</th>
                                    <th>Date & Time</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="Customer">
                                                <div class="customer-cell">
                                                    <i class="fas fa-user-circle"></i>
                                                    <strong><?php echo htmlspecialchars($row['customer_name']); ?></strong>
                                                </div>
                                             </div>
                                            <td data-label="Vehicle">
                                                <div class="vehicle-cell">
                                                    <i class="fas fa-truck"></i>
                                                    <?php echo htmlspecialchars($row['vehicle_no']); ?>
                                                </div>
                                             </div>
                                            <td data-label="Amount Received">
                                                <div class="amount-cell">
                                                    <strong>Rs <?php echo number_format($row['amount'], 2); ?></strong>
                                                </div>
                                             </div>
                                            <td data-label="Payment Method">
                                                <span class="method-badge <?php echo $row['payment_method'] == 'bank' ? 'bank' : 'cash'; ?>">
                                                    <i class="fas <?php echo $row['payment_method'] == 'bank' ? 'fa-university' : 'fa-money-bill-wave'; ?>"></i>
                                                    <?php echo ucfirst($row['payment_method'] ?: 'cash'); ?>
                                                </span>
                                             </div>
                                            <td data-label="Description">
                                                <div class="description-cell">
                                                    <?php if(!empty($row['notes'])): ?>
                                                        <i class="fas fa-file-alt"></i>
                                                        <span><?php echo htmlspecialchars(substr($row['notes'], 0, 50)); ?></span>
                                                        <?php if(strlen($row['notes']) > 50): ?>
                                                            <span class="read-more" title="<?php echo htmlspecialchars($row['notes']); ?>">...</span>
                                                        <?php endif; ?>
                                                    <?php else: ?>
                                                        <span class="no-description">—</span>
                                                    <?php endif; ?>
                                                </div>
                                             </div>
                                            <td data-label="Date & Time">
                                                <div class="date-cell">
                                                    <i class="fas fa-calendar"></i>
                                                    <?php echo date('d-m-Y', strtotime($row['date_time'])); ?>
                                                    <small><?php echo date('H:i', strtotime($row['date_time'])); ?></small>
                                                </div>
                                             </div>
                                        </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="7" class="text-center empty-state">
                                            <i class="fas fa-hand-holding-usd"></i>
                                            <p>No payment records found</p>
                                            <small>Receive payments to see them here</small>
                                         </div>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

* {
    font-family: 'Poppins', sans-serif;
}

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

.receiving-container {
    padding: 0;
}

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

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

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

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

/* Statistics Cards */
.stat-card {
    background: #fff;
    border-radius: 20px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 20px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    transition: all 0.3s;
    border-left: 4px solid #A04657;
}

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

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

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

.stat-info h3 {
    font-size: 24px;
    margin: 0;
    font-weight: bold;
}

.stat-info p {
    margin: 5px 0 0;
    color: #555;
    font-size: 13px;
    font-weight: 600;
}

.stat-trend {
    font-size: 11px;
    color: #999;
    font-weight: 500;
}

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

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

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

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

/* Form Card */
.form-card {
    background: #fff;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 5px 20px rgba(0,0,0,0.05);
    margin-bottom: 20px;
}

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

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

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

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

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

.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;
}

.required {
    color: #dc3545;
}

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

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

textarea.form-control-modern {
    font-family: 'Poppins', sans-serif;
    resize: vertical;
}

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

/* Customer Info Card */
.customer-info-card {
    background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 20px;
    border-left: 4px solid #28a745;
}

.info-row {
    display: flex;
    justify-content: space-between;
    padding: 6px 0;
}

.info-row span {
    font-size: 13px;
    color: #2e7d32;
    font-weight: 500;
}

.info-row strong {
    font-size: 14px;
    color: #1b5e20;
    font-weight: 600;
}

/* Bank Info Box */
.bank-info-box {
    background: #e8f5e9;
    border-radius: 12px;
    padding: 12px 15px;
    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;
}

/* Payment Preview */
.payment-preview {
    background: #e3f2fd;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 20px;
    border-left: 4px solid #2196f3;
}

.preview-title {
    font-weight: 600;
    color: #1565c0;
    margin-bottom: 10px;
    font-size: 13px;
}

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

.preview-row span {
    font-size: 12px;
    color: #1565c0;
}

.preview-row strong {
    font-size: 14px;
    color: #0d47a1;
    font-weight: 600;
}

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

/* Remaining Box */
.remaining-box {
    background: #fff3e0;
    border-radius: 12px;
    padding: 15px;
    margin-bottom: 20px;
    text-align: center;
    border-left: 4px solid #ffc107;
}

.remaining-title {
    font-weight: 600;
    color: #e65100;
    margin-bottom: 10px;
    font-size: 13px;
}

.remaining-amount {
    font-size: 28px;
    font-weight: bold;
    color: #e65100;
    margin-bottom: 5px;
}

.remaining-status {
    font-size: 11px;
    color: #e65100;
}

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

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

/* Info Card */
.info-card {
    background: #f8f9fa;
    border-radius: 15px;
    padding: 20px;
}

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

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

.info-card-header h5 {
    margin: 0;
    font-size: 16px;
}

.info-item {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #e0e0e0;
    font-size: 13px;
    font-weight: 500;
}

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

.info-item span:first-child i {
    margin-right: 8px;
    color: #A04657;
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 5px 20px rgba(0,0,0,0.05);
}

.table-card-header {
    padding: 20px;
    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: 20px;
    color: #A04657;
}

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

.table-search {
    position: relative;
}

.table-search i {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: #999;
}

.search-input {
    padding: 10px 15px 10px 40px;
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    width: 250px;
    transition: all 0.3s;
    font-weight: 500;
}

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

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

.modern-table th {
    padding: 15px;
    background: #f8f9fa;
    font-weight: 600;
    color: #444;
    font-size: 13px;
}

.modern-table td {
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
    font-weight: 500;
    color: #333;
}

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

.customer-cell, .vehicle-cell, .description-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.customer-cell i {
    color: #A04657;
    font-size: 18px;
}

.vehicle-cell i {
    color: #17a2b8;
}

.description-cell i {
    color: #ffc107;
    font-size: 14px;
}

.description-cell span {
    font-size: 12px;
    color: #666;
}

.description-cell .no-description {
    color: #ccc;
}

.description-cell .read-more {
    cursor: pointer;
    color: #A04657;
    font-weight: bold;
}

.amount-cell strong {
    color: #28a745;
    font-size: 16px;
}

.date-cell {
    display: flex;
    flex-direction: column;
    font-size: 12px;
}

.date-cell i {
    margin-right: 5px;
    color: #999;
}

.date-cell small {
    color: #999;
    margin-left: 18px;
    font-size: 10px;
}

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

.empty-state i {
    font-size: 48px;
    color: #A04657;
    margin-bottom: 15px;
}

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

.empty-state small {
    color: #999;
    font-weight: 500;
}

/* Tooltip for long descriptions */
[title] {
    cursor: help;
}

/* Responsive */
@media (max-width: 768px) {
    .page-header {
        flex-direction: column;
        text-align: center;
    }
    
    .table-card-header {
        flex-direction: column;
    }
    
    .search-input {
        width: 100%;
    }
    
    .modern-table th {
        display: none;
    }
    
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 50%;
        position: relative;
    }
    
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 15px;
        width: 45%;
        text-align: left;
        font-weight: 600;
        color: #555;
    }
    
    .remaining-amount {
        font-size: 22px;
    }
}

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

::-webkit-scrollbar-track {
    background: #f1f1f1;
}

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

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

<script>
function updateBalance() {
    var customerSelect = document.getElementById('customer_id');
    var selectedOption = customerSelect.options[customerSelect.selectedIndex];
    var balance = selectedOption.getAttribute('data-balance') || 0;
    var customerName = selectedOption.getAttribute('data-name') || '';
    var customerVehicle = selectedOption.getAttribute('data-vehicle') || '';
    
    // Show customer info card
    if(customerSelect.value) {
        document.getElementById('customerInfoCard').style.display = 'block';
        document.getElementById('customerName').innerHTML = customerName;
        document.getElementById('customerVehicle').innerHTML = customerVehicle;
        document.getElementById('currentBalance').innerHTML = 'Rs ' + parseFloat(balance).toFixed(2);
        document.getElementById('paymentPreview').style.display = 'block';
        document.getElementById('previewCurrentBalance').innerHTML = 'Rs ' + parseFloat(balance).toFixed(2);
    } else {
        document.getElementById('customerInfoCard').style.display = 'none';
        document.getElementById('paymentPreview').style.display = 'none';
        document.getElementById('remainingBox').style.display = 'none';
    }
    
    validateAmount();
}

function validateAmount() {
    var customerSelect = document.getElementById('customer_id');
    var selectedOption = customerSelect.options[customerSelect.selectedIndex];
    var balance = parseFloat(selectedOption.getAttribute('data-balance')) || 0;
    var amount = parseFloat(document.getElementById('amount').value) || 0;
    var remaining = balance - amount;
    var remainingBox = document.getElementById('remainingBox');
    var remainingAmount = document.getElementById('remainingAmount');
    var remainingStatus = document.getElementById('remainingStatus');
    
    if(customerSelect.value) {
        remainingBox.style.display = 'block';
        document.getElementById('previewAmount').innerHTML = 'Rs ' + amount.toFixed(2);
        document.getElementById('previewNewBalance').innerHTML = 'Rs ' + remaining.toFixed(2);
        
        if(amount > balance) {
            remainingAmount.innerHTML = 'Rs ' + remaining.toFixed(2);
            remainingAmount.style.color = '#dc3545';
            remainingStatus.innerHTML = 'Payment amount exceeds customer balance!';
            remainingStatus.style.color = '#dc3545';
            remainingBox.style.borderLeftColor = '#dc3545';
        } else if(amount === balance) {
            remainingAmount.innerHTML = 'Rs 0.00 (Fully Paid)';
            remainingAmount.style.color = '#28a745';
            remainingStatus.innerHTML = 'Customer balance will be cleared!';
            remainingStatus.style.color = '#28a745';
            remainingBox.style.borderLeftColor = '#28a745';
        } else if(amount > 0) {
            remainingAmount.innerHTML = 'Rs ' + remaining.toFixed(2);
            remainingAmount.style.color = '#ffc107';
            remainingStatus.innerHTML = 'Partial payment - Balance remaining';
            remainingStatus.style.color = '#ffc107';
            remainingBox.style.borderLeftColor = '#ffc107';
        } else {
            remainingAmount.innerHTML = 'Rs ' + balance.toFixed(2);
            remainingAmount.style.color = '#ffc107';
            remainingStatus.innerHTML = 'Enter payment amount';
            remainingStatus.style.color = '#ffc107';
        }
        
        // Update bank info if bank payment selected
        if(document.getElementById('payment_method').value === 'bank') {
            updateBankInfo();
        }
    } else {
        remainingBox.style.display = 'none';
    }
}

// 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 customer payments
    const newBalanceSpan = document.getElementById('displayNewBankBalance');
    newBalanceSpan.innerHTML = 'Rs ' + newBalance.toFixed(2);
    newBalanceSpan.style.color = '#28a745';
}

// Initialize on page load
if(document.getElementById('customer_id').value) {
    updateBalance();
}

// Table search functionality
document.getElementById('tableSearch').addEventListener('keyup', function() {
    let searchValue = this.value.toLowerCase();
    let table = document.getElementById('paymentsTable');
    let rows = table.getElementsByTagName('tr');
    
    for (let i = 1; i < rows.length; i++) {
        let row = rows[i];
        let text = row.textContent.toLowerCase();
        if (text.includes(searchValue)) {
            row.style.display = '';
        } else {
            row.style.display = 'none';
        }
    }
});

// Tooltip for read-more
document.querySelectorAll('.read-more').forEach(function(el) {
    el.addEventListener('mouseenter', function() {
        // Native title attribute handles tooltip
    });
});

// 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'); ?>