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

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

$customer_id = isset($_GET['id']) ? mysqli_real_escape_string($conn, $_GET['id']) : 0;
$from_date = isset($_GET['from_date']) ? $_GET['from_date'] : date('Y-m-01');
$to_date = isset($_GET['to_date']) ? $_GET['to_date'] : date('Y-m-d');

// Get customer details
$customer_sql = "SELECT * FROM customers WHERE id='$customer_id'";
$customer_result = mysqli_query($conn, $customer_sql);
$customer = mysqli_fetch_assoc($customer_result);

if(!$customer) {
    header("Location: customers.php");
    exit();
}

// ============================================
// FUEL CREDIT SALES
// ============================================
$credit_sales_sql = "SELECT cs.*, s.shift_name, ft.name as fuel_name, ft.sale_price, 'fuel' as sale_type
                     FROM credit_sales cs
                     LEFT JOIN shift_entries s ON cs.shift_id = s.id
                     LEFT JOIN fuel_types ft ON cs.fuel_type_id = ft.id
                     WHERE cs.customer_id='$customer_id' AND DATE(cs.date_time) BETWEEN '$from_date' AND '$to_date'
                     ORDER BY cs.date_time ASC";
$credit_sales_result = mysqli_query($conn, $credit_sales_sql);

// ============================================
// LUBE CREDIT SALES
// ============================================
$lube_credit_sales_sql = "SELECT ls.*, lp.product_name, lp.product_code, 'lube' as sale_type
                          FROM lube_sales ls
                          LEFT JOIN lube_sale_items lsi ON ls.id = lsi.sale_id
                          LEFT JOIN lube_products lp ON lsi.product_id = lp.id
                          WHERE ls.customer_id='$customer_id' 
                          AND ls.customer_type = 'credit_customer'
                          AND DATE(ls.sale_date) BETWEEN '$from_date' AND '$to_date'
                          ORDER BY ls.sale_date ASC";
$lube_credit_sales_result = mysqli_query($conn, $lube_credit_sales_sql);

// ============================================
// CUSTOMER PAYMENTS (Recovery, Advance, etc.)
// ============================================
$payments_sql = "SELECT * FROM customer_payments 
                 WHERE customer_id='$customer_id' 
                 AND DATE(date_time) BETWEEN '$from_date' AND '$to_date'
                 AND payment_type NOT IN ('opening_balance', 'credit_sale')
                 ORDER BY date_time ASC";
$payments_result = mysqli_query($conn, $payments_sql);

// ============================================
// CALCULATE TOTALS
// ============================================
$total_fuel_credit = 0;
$total_fuel_liters = 0;
$total_lube_credit = 0;
$total_cash_advance = 0;
$total_payments = 0;

// Fuel Credit Totals
while($row = mysqli_fetch_assoc($credit_sales_result)) {
    $total_fuel_credit += $row['amount'];
    $total_fuel_liters += $row['liters'];
}
mysqli_data_seek($credit_sales_result, 0);

// Lube Credit Totals
while($row = mysqli_fetch_assoc($lube_credit_sales_result)) {
    $total_lube_credit += $row['total_amount'];
}
mysqli_data_seek($lube_credit_sales_result, 0);

// Payment Totals
while($row = mysqli_fetch_assoc($payments_result)) {
    if($row['payment_type'] == 'cash_advance') {
        $total_cash_advance += $row['amount'];
    } else {
        $total_payments += $row['amount'];
    }
}
mysqli_data_seek($payments_result, 0);

$total_credit = $total_fuel_credit + $total_lube_credit;
$closing_balance = $customer['balance'];
?>

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

<!-- Customer Ledger Container -->
<div class="customer-ledger-container">
    <!-- Page Header -->
    <div class="page-header">
        <div>
            <h2><i class="fas fa-book"></i> Customer Ledger</h2>
            <p>Complete transaction history for <?php echo htmlspecialchars($customer['name']); ?></p>
        </div>
        <div class="stats-badge">
            <i class="fas fa-rupee-sign"></i> Balance: Rs <?php echo number_format($closing_balance, 2); ?>
        </div>
    </div>

    <!-- Action Buttons -->
    <div class="action-buttons" style="margin-bottom: 20px;">
        <a href="customer_receiving.php?id=<?php echo $customer_id; ?>" class="btn-action-custom btn-success">
            <i class="fas fa-hand-holding-usd"></i> Receive Payment
        </a>
        <a href="credit_sales.php?customer_id=<?php echo $customer_id; ?>" class="btn-action-custom btn-primary">
            <i class="fas fa-shopping-cart"></i> New Fuel Credit Sale
        </a>
        <a href="lube_sales.php?customer_id=<?php echo $customer_id; ?>" class="btn-action-custom btn-info" style="background: #17a2b8;">
            <i class="fas fa-oil-can"></i> New Lube Credit Sale
        </a>
    </div>

    <!-- Filter Card -->
    <div class="filter-card">
        <form method="GET" action="" class="row g-3 align-items-end">
            <input type="hidden" name="id" value="<?php echo $customer_id; ?>">
            <div class="col-md-3">
                <label><i class="fas fa-calendar-alt"></i> From Date</label>
                <input type="date" name="from_date" class="form-control-modern" value="<?php echo $from_date; ?>">
            </div>
            <div class="col-md-3">
                <label><i class="fas fa-calendar-alt"></i> To Date</label>
                <input type="date" name="to_date" class="form-control-modern" value="<?php echo $to_date; ?>">
            </div>
            <div class="col-md-2">
                <button type="submit" class="btn-custom btn-primary-custom w-100">
                    <i class="fas fa-search"></i> Filter
                </button>
            </div>
            <div class="col-md-2">
                <a href="customer_ledger.php?id=<?php echo $customer_id; ?>" class="btn-custom btn-secondary-custom w-100" style="text-align: center;">
                    <i class="fas fa-sync-alt"></i> Reset
                </a>
            </div>
            <div class="col-md-2">
                <button type="button" class="btn-custom btn-print w-100" onclick="window.print()">
                    <i class="fas fa-print"></i> Print
                </button>
            </div>
        </form>
    </div>

    <!-- Customer Info Card -->
    <div class="info-card">
        <div class="info-grid">
            <div class="info-item">
                <span><i class="fas fa-user"></i> Customer Name:</span>
                <strong><?php echo htmlspecialchars($customer['name']); ?></strong>
            </div>
            <div class="info-item">
                <span><i class="fas fa-phone"></i> Phone:</span>
                <strong><?php echo htmlspecialchars($customer['phone'] ?: '—'); ?></strong>
            </div>
            <div class="info-item">
                <span><i class="fas fa-car"></i> Vehicle No:</span>
                <strong><?php echo htmlspecialchars($customer['vehicle_no'] ?: '—'); ?></strong>
            </div>
            <div class="info-item">
                <span><i class="fas fa-money-bill-wave"></i> Advance Balance:</span>
                <strong class="<?php echo $customer['advance_balance'] > 0 ? 'text-success' : 'text-danger'; ?>">
                    Rs <?php echo number_format(abs($customer['advance_balance']), 2); ?>
                </strong>
            </div>
            <div class="info-item">
                <span><i class="fas fa-rupee-sign"></i> Current Balance:</span>
                <strong class="<?php echo $closing_balance > 0 ? 'text-danger' : 'text-success'; ?> balance-amount">
                    Rs <?php echo number_format(abs($closing_balance), 2); ?>
                    <span class="balance-status"><?php echo $closing_balance > 0 ? '(Customer Owes Us)' : '(We Owe Customer)'; ?></span>
                </strong>
            </div>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="stats-row">
        <div class="stat-card">
            <div class="stat-icon bg-warning-light">
                <i class="fas fa-gas-pump text-warning"></i>
            </div>
            <div class="stat-info">
                <h3>Rs <?php echo number_format($total_fuel_credit, 2); ?></h3>
                <p>Fuel Credit Sales</p>
                <span class="stat-trend"><?php echo date('d-m-Y', strtotime($from_date)); ?> to <?php echo date('d-m-Y', strtotime($to_date)); ?></span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon bg-info-light">
                <i class="fas fa-oil-can text-info"></i>
            </div>
            <div class="stat-info">
                <h3>Rs <?php echo number_format($total_lube_credit, 2); ?></h3>
                <p>Lube Credit Sales</p>
                <span class="stat-trend">Lubricant Credit Purchases</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon bg-danger-light">
                <i class="fas fa-money-bill-wave text-danger"></i>
            </div>
            <div class="stat-info">
                <h3>Rs <?php echo number_format($total_cash_advance, 2); ?></h3>
                <p>Cash Advance Given</p>
                <span class="stat-trend">Hard cash given to customer</span>
            </div>
        </div>
        <div class="stat-card">
            <div class="stat-icon bg-success-light">
                <i class="fas fa-hand-holding-usd text-success"></i>
            </div>
            <div class="stat-info">
                <h3>Rs <?php echo number_format($total_payments, 2); ?></h3>
                <p>Payments Received</p>
                <span class="stat-trend">Amount received from customer</span>
            </div>
        </div>
    </div>

    <!-- Ledger Table -->
    <div class="table-card">
        <div class="table-card-header">
            <div class="header-info">
                <i class="fas fa-history"></i>
                <h4>Transaction History</h4>
            </div>
        </div>
        <div class="table-responsive">
            <table class="modern-table">
                <thead>
                    <tr>
                        <th style="width: 50px;">#</th>
                        <th style="width: 160px;">Date & Time</th>
                        <th style="width: 250px;">Description</th>
                        <th style="width: 100px;">Product/Fuel</th>
                        <th style="width: 80px;">Quantity</th>
                        <th style="width: 100px;">Rate (Rs)</th>
                        <th style="width: 130px;">Transaction Type</th>
                        <th style="width: 150px;">Debit (Customer Owes)</th>
                        <th style="width: 150px;">Credit (Customer Paid)</th>
                        <th style="width: 130px;">Balance</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $running_balance = 0;
                    $counter = 1;
                    $transactions = [];
                    
                    // Add opening balance if exists
                    if($customer['balance'] != 0) {
                        $opening_balance = $customer['balance'];
                        $running_balance = $opening_balance;
                        echo '<tr class="opening-row">
                            <td data-label="#">'.($counter++).'</td>
                            <td data-label="Date & Time">'.date('d-m-Y', strtotime($customer['date_time'])).'</td>
                            <td data-label="Description"><strong>Opening Balance</strong></td>
                            <td data-label="Product/Fuel">-</td>
                            <td data-label="Quantity">-</td>
                            <td data-label="Rate">-</td>
                            <td data-label="Transaction Type"><span class="status-badge opening">Opening</span></td>
                            <td data-label="Debit" class="debit-amount text-right">Rs '.number_format($opening_balance, 2).'</td>
                            <td data-label="Credit">-</td>
                            <td data-label="Balance" class="balance-amount-cell text-right"><strong>Rs '.number_format($running_balance, 2).'</strong></td>
                        </tr>';
                    }
                    
                    // ============================================
                    // ADD FUEL CREDIT SALES
                    // ============================================
                    while($sale = mysqli_fetch_assoc($credit_sales_result)) {
                        $fuel_name = $sale['fuel_name'] ? $sale['fuel_name'] : 'Fuel';
                        $rate = ($sale['liters'] > 0) ? ($sale['amount'] / $sale['liters']) : 0;
                        $transactions[] = [
                            'date' => $sale['date_time'],
                            'description' => 'Fuel Purchase - ' . $sale['shift_name'] . ' Shift',
                            'product_name' => $fuel_name,
                            'quantity' => $sale['liters'],
                            'quantity_unit' => 'L',
                            'rate' => $rate,
                            'type' => 'Fuel Sale',
                            'type_class' => 'sale',
                            'type_icon' => 'fa-gas-pump',
                            'debit' => $sale['amount'],
                            'credit' => 0
                        ];
                    }
                    
                    // ============================================
                    // ADD LUBE CREDIT SALES
                    // ============================================
                    $current_lube_sale_id = null;
                    $lube_sale_items = [];
                    
                    // First, get all lube sales and group items
                    mysqli_data_seek($lube_credit_sales_result, 0);
                    while($lube_sale = mysqli_fetch_assoc($lube_credit_sales_result)) {
                        $sale_id = $lube_sale['id'];
                        if(!isset($lube_sale_items[$sale_id])) {
                            $lube_sale_items[$sale_id] = [
                                'sale_invoice' => $lube_sale['sale_invoice'],
                                'sale_date' => $lube_sale['sale_date'],
                                'total_amount' => $lube_sale['total_amount'],
                                'items' => []
                            ];
                        }
                        if($lube_sale['product_name']) {
                            $lube_sale_items[$sale_id]['items'][] = [
                                'product_name' => $lube_sale['product_name'],
                                'product_code' => $lube_sale['product_code'],
                                'quantity' => $lube_sale['quantity'],
                                'sale_price' => $lube_sale['sale_price']
                            ];
                        }
                    }
                    
                    // Add lube sales transactions
                    foreach($lube_sale_items as $sale_id => $sale_data) {
                        $items_count = count($sale_data['items']);
                        $item_text = '';
                        foreach($sale_data['items'] as $idx => $item) {
                            $item_text .= $item['product_name'] . ' (' . number_format($item['quantity'], 2) . ' L)';
                            if($idx < $items_count - 1) $item_text .= ', ';
                        }
                        
                        $transactions[] = [
                            'date' => $sale_data['sale_date'],
                            'description' => 'Lube Purchase - Invoice: ' . $sale_data['sale_invoice'],
                            'product_name' => $item_text,
                            'quantity' => '-',
                            'quantity_unit' => '',
                            'rate' => '-',
                            'type' => 'Lube Sale',
                            'type_class' => 'lube-sale',
                            'type_icon' => 'fa-oil-can',
                            'debit' => $sale_data['total_amount'],
                            'credit' => 0
                        ];
                    }
                    
                    // ============================================
                    // ADD PAYMENTS AND CASH ADVANCES
                    // ============================================
                    while($payment = mysqli_fetch_assoc($payments_result)) {
                        if($payment['payment_type'] == 'cash_advance') {
                            $transactions[] = [
                                'date' => $payment['date_time'],
                                'description' => '💰 Cash Advance Given' . ($payment['notes'] ? ' (' . $payment['notes'] . ')' : ''),
                                'product_name' => '-',
                                'quantity' => '-',
                                'quantity_unit' => '',
                                'rate' => '-',
                                'type' => 'Cash Advance',
                                'type_class' => 'cash-advance',
                                'type_icon' => 'fa-money-bill-wave',
                                'debit' => $payment['amount'],
                                'credit' => 0
                            ];
                        } elseif($payment['payment_type'] == 'advance') {
                            $transactions[] = [
                                'date' => $payment['date_time'],
                                'description' => 'Advance Payment Received' . ($payment['notes'] ? ' (' . $payment['notes'] . ')' : ''),
                                'product_name' => '-',
                                'quantity' => '-',
                                'quantity_unit' => '',
                                'rate' => '-',
                                'type' => 'Advance Payment',
                                'type_class' => 'payment',
                                'type_icon' => 'fa-hand-holding-usd',
                                'debit' => 0,
                                'credit' => $payment['amount']
                            ];
                        } elseif($payment['payment_type'] == 'payment') {
                            $transactions[] = [
                                'date' => $payment['date_time'],
                                'description' => 'Payment Received' . ($payment['notes'] ? ' (' . $payment['notes'] . ')' : ''),
                                'product_name' => '-',
                                'quantity' => '-',
                                'quantity_unit' => '',
                                'rate' => '-',
                                'type' => 'Payment',
                                'type_class' => 'payment',
                                'type_icon' => 'fa-check-circle',
                                'debit' => 0,
                                'credit' => $payment['amount']
                            ];
                        }
                    }
                    
                    // Sort transactions by date
                    usort($transactions, function($a, $b) { 
                        return strtotime($a['date']) - strtotime($b['date']); 
                    });
                    
                    if(count($transactions) > 0) {
                        foreach($transactions as $trans) {
                            $running_balance += $trans['debit'] - $trans['credit'];
                            $date_display = date('d-m-Y h:i:s A', strtotime($trans['date']));
                            
                            echo '<tr>
                                <td data-label="#">'.($counter++).'</td>
                                <td data-label="Date & Time">'.$date_display.'</td>
                                <td data-label="Description">';
                            if($trans['debit'] > 0 && $trans['credit'] == 0 && $trans['type'] != 'Fuel Sale' && $trans['type'] != 'Lube Sale') {
                                echo '<i class="fas fa-arrow-up text-danger"></i> ';
                            } elseif($trans['credit'] > 0) {
                                echo '<i class="fas fa-arrow-down text-success"></i> ';
                            } elseif($trans['type'] == 'Fuel Sale') {
                                echo '<i class="fas fa-gas-pump text-warning"></i> ';
                            } elseif($trans['type'] == 'Lube Sale') {
                                echo '<i class="fas fa-oil-can text-info"></i> ';
                            }
                            echo $trans['description'].'</td>
                                <td data-label="Product/Fuel">';
                                if($trans['product_name'] != '-') {
                                    echo '<span class="fuel-badge"><i class="fas '.$trans['type_icon'].'"></i> '.htmlspecialchars(substr($trans['product_name'], 0, 30)).'</span>';
                                } else {
                                    echo '-';
                                }
                            echo '</td>
                                <td data-label="Quantity" class="text-right">'.($trans['quantity'] != '-' ? number_format($trans['quantity'], 2) . ' ' . $trans['quantity_unit'] : '-').'</td>
                                <td data-label="Rate" class="text-right">'.($trans['rate'] != '-' ? 'Rs '.number_format($trans['rate'], 2) : '-').'</td>
                                <td data-label="Transaction Type"><span class="status-badge '.$trans['type_class'].'"><i class="fas '.$trans['type_icon'].'"></i> '.$trans['type'].'</span></td>
                                <td data-label="Debit" class="debit-amount text-right">'.($trans['debit'] > 0 ? 'Rs '.number_format($trans['debit'], 2) : '-').'</td>
                                <td data-label="Credit" class="credit-amount text-right">'.($trans['credit'] > 0 ? 'Rs '.number_format($trans['credit'], 2) : '-').'</td>
                                <td data-label="Balance" class="balance-amount-cell text-right"><strong>Rs '.number_format($running_balance, 2).'</strong></td>
                            </tr>';
                        }
                    } else {
                        echo '<tr><td colspan="10" class="empty-state"><i class="fas fa-exchange-alt"></i><p>No transactions found for the selected period</p></td></tr>';
                    }
                    ?>
                </tbody>
                <tfoot>
                    <tr class="total-row">
                        <td colspan="7"><strong>TOTAL SUMMARY</strong></td>
                        <td class="debit-amount text-right"><strong>Rs <?php echo number_format($total_credit + $total_cash_advance, 2); ?></strong></td>
                        <td class="credit-amount text-right"><strong>Rs <?php echo number_format($total_payments, 2); ?></strong></td>
                        <td class="balance-amount-cell text-right"><strong>Rs <?php echo number_format($closing_balance, 2); ?></strong></td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
    
    <div class="back-button">
        <a href="customers.php" class="btn-custom btn-secondary-custom">
            <i class="fas fa-arrow-left"></i> Back to Customers
        </a>
    </div>
</div>

<style>
/* Customer Ledger Styles - Same as Tanks CSS */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');

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

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

/* Container - NO EXTRA SPACING */
.customer-ledger-container {
    width: 100%;
    max-width: 100%;
    margin: 0;
    padding: 20px 30px;
}

/* 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;
    box-shadow: 0 4px 15px rgba(160,70,87,0.2);
    width: 100%;
}

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

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

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

/* Action Buttons */
.action-buttons {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    margin-bottom: 20px;
}

.btn-action-custom {
    padding: 10px 20px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 12px;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 8px;
    transition: all 0.2s;
}

.btn-action-custom:hover {
    transform: translateY(-2px);
}

.btn-success {
    background: #28a745;
    color: #fff;
}

.btn-primary {
    background: #A04657;
    color: #fff;
}

.btn-info {
    background: #17a2b8;
    color: #fff;
}

/* Filter Card */
.filter-card {
    background: #fff;
    border-radius: 14px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    border: 1px solid #eee;
}

.filter-card label {
    font-weight: 600;
    margin-bottom: 5px;
    color: #333;
    font-size: 12px;
}

.filter-card label i {
    color: #A04657;
    margin-right: 5px;
}

.form-control-modern {
    width: 100%;
    padding: 9px 12px;
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    font-size: 13px;
    transition: all 0.2s;
    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);
}

/* Info Card */
.info-card {
    background: #fff;
    border-radius: 14px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    border: 1px solid #eee;
}

.info-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 15px;
}

.info-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px solid #f0f0f0;
}

.info-item span {
    color: #666;
    font-weight: 500;
    font-size: 12px;
}

.info-item span i {
    color: #A04657;
    width: 20px;
}

.info-item strong {
    color: #333;
    font-size: 13px;
    font-weight: 600;
}

.balance-amount {
    font-size: 16px;
    font-weight: 700;
}

.balance-status {
    font-size: 11px;
    font-weight: normal;
    margin-left: 5px;
}

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

.stat-card {
    background: #fff;
    border-radius: 14px;
    padding: 15px 18px;
    display: flex;
    align-items: center;
    gap: 15px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    border-left: 4px solid #A04657;
    transition: all 0.3s;
}

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

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 14px;
    display: flex;
    align-items: center;
    justify-content: center;
}

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

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

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

.stat-trend {
    font-size: 9px;
    color: #999;
    display: block;
    margin-top: 2px;
}

.bg-warning-light { background: rgba(255,193,7,0.1); }
.bg-info-light { background: rgba(23,162,184,0.1); }
.bg-danger-light { background: rgba(220,53,69,0.1); }
.bg-success-light { background: rgba(40,167,69,0.1); }
.text-warning { color: #ffc107 !important; }
.text-info { color: #17a2b8 !important; }
.text-danger { color: #dc3545 !important; }
.text-success { color: #28a745 !important; }

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 14px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    border: 1px solid #eee;
    width: 100%;
    margin-bottom: 20px;
}

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

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

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

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

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

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

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

.modern-table td {
    padding: 9px 10px;
    border-bottom: 1px solid #f0f0f0;
    vertical-align: middle;
}

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

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

/* Status Badges */
.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 4px;
    padding: 3px 10px;
    border-radius: 15px;
    font-size: 9px;
    font-weight: 600;
    white-space: nowrap;
}

.status-badge.opening { background: #17a2b8; color: #fff; }
.status-badge.sale { background: #ffc107; color: #333; }
.status-badge.lube-sale { background: #17a2b8; color: #fff; }
.status-badge.payment { background: #28a745; color: #fff; }
.status-badge.cash-advance { background: #dc3545; color: #fff; }

.fuel-badge {
    background: #e8eaf6;
    color: #3f51b5;
    padding: 3px 8px;
    border-radius: 12px;
    font-size: 10px;
    display: inline-flex;
    align-items: center;
    gap: 4px;
}

.debit-amount { color: #dc3545; font-weight: 600; }
.credit-amount { color: #28a745; font-weight: 600; }
.balance-amount-cell { font-weight: 700; color: #1a1a2e; }

.opening-row {
    background: #e3f2fd;
}

.total-row {
    background: #f8f9fa;
    font-weight: bold;
}

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

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

/* Buttons */
.btn-custom {
    padding: 8px 16px;
    border-radius: 8px;
    font-weight: 600;
    font-size: 12px;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.2s;
    border: none;
    cursor: pointer;
}

.btn-custom:hover {
    transform: translateY(-2px);
}

.btn-primary-custom {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    color: #fff;
}

.btn-secondary-custom {
    background: #6c757d;
    color: #fff;
}

.btn-print {
    background: #28a745;
    color: #fff;
}

.w-100 {
    width: 100%;
}

.back-button {
    margin-top: 10px;
}

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

@media (max-width: 992px) {
    .customer-ledger-container {
        padding: 15px;
    }
}

@media (max-width: 768px) {
    .customer-ledger-container {
        padding: 12px;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 12px;
        padding: 15px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .stats-row {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .stat-card {
        padding: 12px 15px;
    }
    .stat-icon {
        width: 40px;
        height: 40px;
    }
    .stat-icon i {
        font-size: 18px;
    }
    .stat-info h3 {
        font-size: 18px;
    }
    .info-grid {
        grid-template-columns: 1fr;
    }
    .table-card-header {
        flex-direction: column;
        align-items: stretch;
    }
    .modern-table th {
        display: none;
    }
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 45%;
        position: relative;
    }
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 10px;
        width: 40%;
        text-align: left;
        font-weight: 700;
        font-size: 10px;
        color: #A04657;
    }
    .modern-table tr {
        display: block;
        margin-bottom: 10px;
        border: 1px solid #e8e8e8;
        border-radius: 10px;
        overflow: hidden;
    }
    .action-buttons {
        justify-content: center;
    }
}

@media print {
    .sidebar, .filter-card, .action-buttons, .back-button {
        display: none !important;
    }
    .customer-ledger-container {
        padding: 0 !important;
        margin: 0 !important;
    }
    .page-header {
        background: #A04657 !important;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
}

/* Scrollbar */
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}
::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 10px;
}
::-webkit-scrollbar-thumb {
    background: #A04657;
    border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
    background: #6b2a36;
}
</style>

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