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

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

// ============================================
// OPENING BALANCE MANAGEMENT
// ============================================

// Check if opening_balance table exists, if not create it
$check_table = "SHOW TABLES LIKE 'cashbook_opening_balance'";
$table_exists = mysqli_query($conn, $check_table);
if(mysqli_num_rows($table_exists) == 0) {
    $create_table = "CREATE TABLE `cashbook_opening_balance` (
        `id` int NOT NULL AUTO_INCREMENT,
        `opening_balance` decimal(12,2) NOT NULL DEFAULT '0.00',
        `date` date NOT NULL,
        `notes` text,
        `updated_by` varchar(50) DEFAULT NULL,
        `updated_at` varchar(50) NOT NULL,
        PRIMARY KEY (`id`)
    )";
    mysqli_query($conn, $create_table);
    
    // Insert default opening balance
    $default_insert = "INSERT INTO cashbook_opening_balance (opening_balance, date, updated_at) VALUES (0, CURDATE(), NOW())";
    mysqli_query($conn, $default_insert);
}

// Get current opening balance
$opening_balance_sql = "SELECT opening_balance FROM cashbook_opening_balance ORDER BY id DESC LIMIT 1";
$opening_balance_result = mysqli_query($conn, $opening_balance_sql);
$current_opening_balance = 0;
if($opening_balance_result && mysqli_num_rows($opening_balance_result) > 0) {
    $opening_data = mysqli_fetch_assoc($opening_balance_result);
    $current_opening_balance = $opening_data['opening_balance'];
}

// Update opening balance
if($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['update_opening_balance'])) {
    $new_opening_balance = mysqli_real_escape_string($conn, $_POST['opening_balance']);
    $notes = mysqli_real_escape_string($conn, $_POST['notes']);
    $updated_by = $_SESSION['username'];
    $updated_at = date('Y-m-d H:i:s');
    $current_date = date('Y-m-d');
    
    $insert_sql = "INSERT INTO cashbook_opening_balance (opening_balance, date, notes, updated_by, updated_at) 
                   VALUES ('$new_opening_balance', '$current_date', '$notes', '$updated_by', '$updated_at')";
    
    if(mysqli_query($conn, $insert_sql)) {
        $current_opening_balance = $new_opening_balance;
        $success_message = "Opening balance updated successfully!";
    } else {
        $error_message = "Error: " . mysqli_error($conn);
    }
}

// ============================================
// FUEL SALES LOGIC - WITH PROPER FUEL PRICES
// ============================================

// 1. TOTAL FUEL SALES VALUE (from nozzle_readings with proper fuel prices)
$total_sales_sql = "SELECT 
                    nr.id,
                    nr.sale_liters,
                    ft.sale_price,
                    (nr.sale_liters * ft.sale_price) as sale_value
                    FROM nozzle_readings nr
                    LEFT JOIN nozzles n ON nr.nozzle_id = n.id
                    LEFT JOIN tanks t ON n.tank_id = t.id
                    LEFT JOIN fuel_types ft ON t.fuel_type_id = ft.id";
$total_sales_result = mysqli_query($conn, $total_sales_sql);

$total_sales_value = 0;
$total_liters_sold = 0;

if($total_sales_result && mysqli_num_rows($total_sales_result) > 0) {
    while($sale = mysqli_fetch_assoc($total_sales_result)) {
        $total_liters_sold += $sale['sale_liters'];
        $total_sales_value += $sale['sale_value'];
    }
}

// 2. CREDIT SALES (from credit_sales table - FUEL ONLY)
$credit_sales_sql = "SELECT SUM(amount) as total_credit_amount,
                     SUM(liters) as total_credit_liters
                     FROM credit_sales";
$credit_sales_result = mysqli_query($conn, $credit_sales_sql);
$credit_sales_data = mysqli_fetch_assoc($credit_sales_result);
$total_credit_sales = ($credit_sales_data['total_credit_amount']) ? $credit_sales_data['total_credit_amount'] : 0;
$total_credit_liters = ($credit_sales_data['total_credit_liters']) ? $credit_sales_data['total_credit_liters'] : 0;

// 3. Get detailed fuel sales breakdown by fuel type
$fuel_breakdown_sql = "SELECT 
                        ft.name as fuel_name,
                        ft.sale_price,
                        SUM(nr.sale_liters) as total_liters,
                        SUM(nr.sale_liters * ft.sale_price) as total_value
                        FROM nozzle_readings nr
                        LEFT JOIN nozzles n ON nr.nozzle_id = n.id
                        LEFT JOIN tanks t ON n.tank_id = t.id
                        LEFT JOIN fuel_types ft ON t.fuel_type_id = ft.id
                        GROUP BY ft.id, ft.name, ft.sale_price
                        ORDER BY ft.name";
$fuel_breakdown_result = mysqli_query($conn, $fuel_breakdown_sql);

// 4. FUEL CASH SALES (CALCULATED)
$fuel_cash_sales = $total_sales_value - $total_credit_sales;
$fuel_cash_liters = $total_liters_sold - $total_credit_liters;

// ============================================
// LUBE SALES - ONLY CASH (WALK-IN) SALES FOR CASHBOOK
// ============================================

// 5. LUBE CASH SALES (Walk-in sales only - actual cash inflow)
$lube_cash_sales_sql = "SELECT SUM(total_amount) as total_lube_cash_sales
                        FROM lube_sales 
                        WHERE customer_type = 'walkin'";
$lube_cash_sales_result = mysqli_query($conn, $lube_cash_sales_sql);
$lube_cash_sales_data = mysqli_fetch_assoc($lube_cash_sales_result);
$total_lube_cash_sales = ($lube_cash_sales_data['total_lube_cash_sales']) ? $lube_cash_sales_data['total_lube_cash_sales'] : 0;

// 6. LUBE CREDIT SALES - NOT FOR CASHBOOK (for information only)
$lube_credit_sales_sql = "SELECT SUM(total_amount) as total_lube_credit_sales
                          FROM lube_sales 
                          WHERE customer_type = 'credit_customer'";
$lube_credit_sales_result = mysqli_query($conn, $lube_credit_sales_sql);
$lube_credit_sales_data = mysqli_fetch_assoc($lube_credit_sales_result);
$total_lube_credit_sales = ($lube_credit_sales_data['total_lube_credit_sales']) ? $lube_credit_sales_data['total_lube_credit_sales'] : 0;

// 7. LUBE CASH SALES (for display)
$lube_cash_sales = $total_lube_cash_sales;

// 8. LUBE STOCK VALUE (for information only)
$lube_stock_sql = "SELECT SUM(current_stock * purchase_price) as total_stock_value FROM lube_products";
$lube_stock_result = mysqli_query($conn, $lube_stock_sql);
$lube_stock_data = mysqli_fetch_assoc($lube_stock_result);
$total_lube_stock_value = ($lube_stock_data['total_stock_value']) ? $lube_stock_data['total_stock_value'] : 0;

// 9. LUBE CASH PURCHASES (Payment to suppliers for lube - Cash OUTFLOW)
$lube_purchases_sql = "SELECT SUM(total_amount) as total_lube_purchases
                       FROM lube_purchases 
                       WHERE payment_type = 'cash'";
$lube_purchases_result = mysqli_query($conn, $lube_purchases_sql);
$lube_purchases_data = mysqli_fetch_assoc($lube_purchases_result);
$total_lube_purchases = ($lube_purchases_data['total_lube_purchases']) ? $lube_purchases_data['total_lube_purchases'] : 0;

// ============================================
// TOTAL CASH SALES (Fuel Cash + Lube Cash Sales)
// ============================================
$total_cash_sales = $fuel_cash_sales + $lube_cash_sales;

// ============================================
// EMPLOYEE LEDGER INTEGRATION
// ============================================

// 10. EMPLOYEE PAYMENTS TOTAL (Salary + Advance + Bonus - Cash OUTFLOW)
$employee_payments_sql = "SELECT SUM(amount) as total_employee_payments 
                          FROM employee_ledger 
                          WHERE entry_type IN ('Salary', 'Advance', 'Bonus')";
$employee_payments_result = mysqli_query($conn, $employee_payments_sql);
$employee_payments_data = mysqli_fetch_assoc($employee_payments_result);
$total_employee_payments = ($employee_payments_data['total_employee_payments']) ? $employee_payments_data['total_employee_payments'] : 0;

// 11. EMPLOYEE RECOVERY TOTAL (Cash INFLOW)
$employee_recovery_sql = "SELECT SUM(amount) as total_employee_recovery 
                          FROM employee_ledger 
                          WHERE entry_type = 'Recovery'";
$employee_recovery_result = mysqli_query($conn, $employee_recovery_sql);
$employee_recovery_data = mysqli_fetch_assoc($employee_recovery_result);
$total_employee_recovery = ($employee_recovery_data['total_employee_recovery']) ? $employee_recovery_data['total_employee_recovery'] : 0;

// 12. Get Employee Summary Statistics
$employee_stats_sql = "SELECT 
                        COUNT(id) as total_employees,
                        SUM(balance) as total_outstanding_balance
                       FROM employees";
$employee_stats_result = mysqli_query($conn, $employee_stats_sql);
$employee_stats = mysqli_fetch_assoc($employee_stats_result);
$total_employees = $employee_stats['total_employees'] ? $employee_stats['total_employees'] : 0;
$total_employee_outstanding = $employee_stats['total_outstanding_balance'] ? $employee_stats['total_outstanding_balance'] : 0;

// 13. Get recent employee transactions
$recent_employee_entries_sql = "SELECT el.*, e.employee_name 
                                FROM employee_ledger el
                                LEFT JOIN employees e ON el.employee_id = e.id
                                ORDER BY el.id DESC 
                                LIMIT 10";
$recent_employee_entries_result = mysqli_query($conn, $recent_employee_entries_sql);

// ============================================
// EXPENSES & OTHER TRANSACTIONS
// ============================================

// 14. EXPENSES (from expenses table)
$expenses_sql = "SELECT SUM(amount) as total_expenses FROM expenses";
$expenses_result = mysqli_query($conn, $expenses_sql);
$expenses_data = mysqli_fetch_assoc($expenses_result);
$total_expenses = ($expenses_data['total_expenses']) ? $expenses_data['total_expenses'] : 0;

if($total_expenses == 0) {
    $expenses_sql2 = "SELECT SUM(expense_amount) as total_expenses FROM expenses";
    $expenses_result2 = mysqli_query($conn, $expenses_sql2);
    if($expenses_result2) {
        $expenses_data2 = mysqli_fetch_assoc($expenses_result2);
        $total_expenses = ($expenses_data2['total_expenses']) ? $expenses_data2['total_expenses'] : 0;
    }
}

// 15. SUPPLIER PAYMENTS (Fuel supplier payments - Cash OUTFLOW)
$supplier_payments_sql = "SELECT SUM(amount) as total_supplier_payments FROM supplier_payments";
$supplier_payments_result = mysqli_query($conn, $supplier_payments_sql);
if($supplier_payments_result) {
    $supplier_payments_data = mysqli_fetch_assoc($supplier_payments_result);
    $total_supplier_payments = ($supplier_payments_data['total_supplier_payments']) ? $supplier_payments_data['total_supplier_payments'] : 0;
} else {
    $total_supplier_payments = 0;
}

// 16. CUSTOMER RECOVERY (Cash INFLOW)
$recovery_sql = "SELECT SUM(amount) as total_recovery FROM customer_payments WHERE payment_type = 'payment'";
$recovery_result = mysqli_query($conn, $recovery_sql);
if($recovery_result) {
    $recovery_data = mysqli_fetch_assoc($recovery_result);
    $total_recovery = ($recovery_data['total_recovery']) ? $recovery_data['total_recovery'] : 0;
} else {
    $total_recovery = 0;
}

// 17. CUSTOMER ADVANCE (Cash INFLOW)
$advance_sql = "SELECT SUM(amount) as total_advance FROM customer_payments WHERE payment_type = 'advance'";
$advance_result = mysqli_query($conn, $advance_sql);
if($advance_result) {
    $advance_data = mysqli_fetch_assoc($advance_result);
    $total_advance = ($advance_data['total_advance']) ? $advance_data['total_advance'] : 0;
} else {
    $total_advance = 0;
}

// 18. GP PAID (We paid to party - Cash OUTFLOW)
$gp_paid_sql = "SELECT SUM(amount) as total_gp_paid FROM gp_paid";
$gp_paid_result = mysqli_query($conn, $gp_paid_sql);
if($gp_paid_result) {
    $gp_paid_data = mysqli_fetch_assoc($gp_paid_result);
    $total_gp_paid = ($gp_paid_data['total_gp_paid']) ? $gp_paid_data['total_gp_paid'] : 0;
} else {
    $total_gp_paid = 0;
}

// 19. GP RECEIVED (Party paid us - Cash INFLOW)
$gp_received_sql = "SELECT SUM(amount) as total_gp_received FROM gp_received";
$gp_received_result = mysqli_query($conn, $gp_received_sql);
if($gp_received_result) {
    $gp_received_data = mysqli_fetch_assoc($gp_received_result);
    $total_gp_received = ($gp_received_data['total_gp_received']) ? $gp_received_data['total_gp_received'] : 0;
} else {
    $total_gp_received = 0;
}

// ============================================
// TOTAL CASH INFLOWS (Cash coming IN)
// ============================================
$total_cash_inflows = $current_opening_balance + $fuel_cash_sales + $lube_cash_sales + $total_recovery + $total_advance + $total_gp_received + $total_employee_recovery;

// ============================================
// TOTAL CASH OUTFLOWS (Cash going OUT)
// ============================================
$total_cash_outflows = $total_expenses + $total_supplier_payments + $total_gp_paid + $total_lube_purchases + $total_employee_payments;

// 20. NET CASH (Closing Balance)
$net_cash = $total_cash_inflows - $total_cash_outflows;

// ============================================
// DETAILS FOR TABLES
// ============================================

// Get supplier payments details
$supplier_details_result = null;
$supplier_details_sql = "SELECT sp.*, s.name as supplier_name 
                         FROM supplier_payments sp
                         LEFT JOIN suppliers s ON sp.supplier_id = s.id
                         ORDER BY sp.id DESC 
                         LIMIT 10";
$supplier_details_result = mysqli_query($conn, $supplier_details_sql);

// Get expenses details
$expenses_details_sql = "SELECT * FROM expenses ORDER BY id DESC LIMIT 10";
$expenses_details_result = mysqli_query($conn, $expenses_details_sql);

// Get advance payments details
$advance_details_sql = "SELECT cp.*, c.name as customer_name 
                        FROM customer_payments cp
                        LEFT JOIN customers c ON cp.customer_id = c.id
                        WHERE cp.payment_type = 'advance'
                        ORDER BY cp.id DESC 
                        LIMIT 10";
$advance_details_result = mysqli_query($conn, $advance_details_sql);

// Get GP Paid details
$gp_paid_details_sql = "SELECT gp.*, gp.amount, gp.date_time, gp.description, gp.user_name
                        FROM gp_paid gp
                        ORDER BY gp.id DESC 
                        LIMIT 10";
$gp_paid_details_result = mysqli_query($conn, $gp_paid_details_sql);

// Get GP Received details
$gp_received_details_sql = "SELECT gr.*, gr.amount, gr.date_time, gr.description, gr.user_name
                            FROM gp_received gr
                            ORDER BY gr.id DESC 
                            LIMIT 10";
$gp_received_details_result = mysqli_query($conn, $gp_received_details_sql);

// Get detailed nozzle readings
$nozzle_details_sql = "SELECT nr.*, n.nozzle_name, t.tank_name, ft.name as fuel_name, ft.sale_price
                       FROM nozzle_readings nr
                       LEFT JOIN nozzles n ON nr.nozzle_id = n.id
                       LEFT JOIN tanks t ON n.tank_id = t.id
                       LEFT JOIN fuel_types ft ON t.fuel_type_id = ft.id
                       ORDER BY nr.id DESC 
                       LIMIT 10";
$nozzle_details_result = mysqli_query($conn, $nozzle_details_sql);

// Get credit sales details (FUEL ONLY)
$credit_details_sql = "SELECT cs.*, c.name as customer_name 
                       FROM credit_sales cs
                       LEFT JOIN customers c ON cs.customer_id = c.id
                       ORDER BY cs.id DESC 
                       LIMIT 10";
$credit_details_result = mysqli_query($conn, $credit_details_sql);

// Get lube cash sales details (Walk-in only - actual cash inflow)
$lube_sales_details_sql = "SELECT ls.*, c.name as customer_name 
                           FROM lube_sales ls
                           LEFT JOIN customers c ON ls.customer_id = c.id
                           WHERE ls.customer_type = 'walkin'
                           ORDER BY ls.id DESC 
                           LIMIT 10";
$lube_sales_details_result = mysqli_query($conn, $lube_sales_details_sql);

// Get lube purchases details
$lube_purchases_details_sql = "SELECT lp.*, s.name as supplier_name 
                               FROM lube_purchases lp
                               LEFT JOIN suppliers s ON lp.supplier_id = s.id
                               WHERE lp.payment_type = 'cash'
                               ORDER BY lp.id DESC 
                               LIMIT 10";
$lube_purchases_details_result = mysqli_query($conn, $lube_purchases_details_sql);

// Today's statistics
$today_date = date('Y-m-d');
$today_fuel_sales_sql = "SELECT 
                         SUM(nr.sale_liters) as today_liters,
                         SUM(nr.sale_liters * ft.sale_price) as today_value
                         FROM nozzle_readings nr
                         LEFT JOIN nozzles n ON nr.nozzle_id = n.id
                         LEFT JOIN tanks t ON n.tank_id = t.id
                         LEFT JOIN fuel_types ft ON t.fuel_type_id = ft.id
                         WHERE nr.date_time LIKE '$today_date%'";
$today_fuel_sales_result = mysqli_query($conn, $today_fuel_sales_sql);
$today_fuel_sales_data = mysqli_fetch_assoc($today_fuel_sales_result);
$today_fuel_liters = ($today_fuel_sales_data['today_liters']) ? $today_fuel_sales_data['today_liters'] : 0;
$today_fuel_sales_value = ($today_fuel_sales_data['today_value']) ? $today_fuel_sales_data['today_value'] : 0;

// Today's lube cash sales (Walk-in only)
$today_lube_sales_sql = "SELECT SUM(total_amount) as today_lube_sales
                         FROM lube_sales 
                         WHERE customer_type = 'walkin' 
                         AND DATE(sale_date) = '$today_date'";
$today_lube_sales_result = mysqli_query($conn, $today_lube_sales_sql);
$today_lube_sales_data = mysqli_fetch_assoc($today_lube_sales_result);
$today_lube_sales_value = ($today_lube_sales_data['today_lube_sales']) ? $today_lube_sales_data['today_lube_sales'] : 0;

$today_total_sales = $today_fuel_sales_value + $today_lube_sales_value;

// Today's supplier payments
$today_supplier_payments = 0;
$today_supplier_payments_sql = "SELECT SUM(amount) as today_payments FROM supplier_payments WHERE date_time LIKE '$today_date%'";
$today_supplier_payments_result = mysqli_query($conn, $today_supplier_payments_sql);
if($today_supplier_payments_result) {
    $today_supplier_payments_data = mysqli_fetch_assoc($today_supplier_payments_result);
    $today_supplier_payments = ($today_supplier_payments_data['today_payments']) ? $today_supplier_payments_data['today_payments'] : 0;
}

// Today's lube purchases
$today_lube_purchases = 0;
$today_lube_purchases_sql = "SELECT SUM(total_amount) as today_purchases FROM lube_purchases WHERE payment_type = 'cash' AND DATE(created_at) = '$today_date'";
$today_lube_purchases_result = mysqli_query($conn, $today_lube_purchases_sql);
if($today_lube_purchases_result) {
    $today_lube_purchases_data = mysqli_fetch_assoc($today_lube_purchases_result);
    $today_lube_purchases = ($today_lube_purchases_data['today_purchases']) ? $today_lube_purchases_data['today_purchases'] : 0;
}

// Today's advance payments
$today_advance = 0;
$today_advance_sql = "SELECT SUM(amount) as today_advance FROM customer_payments WHERE payment_type = 'advance' AND date_time LIKE '$today_date%'";
$today_advance_result = mysqli_query($conn, $today_advance_sql);
if($today_advance_result) {
    $today_advance_data = mysqli_fetch_assoc($today_advance_result);
    $today_advance = ($today_advance_data['today_advance']) ? $today_advance_data['today_advance'] : 0;
}

// Today's GP Received
$today_gp_received = 0;
$today_gp_received_sql = "SELECT SUM(amount) as today_gp_received FROM gp_received WHERE date_time LIKE '$today_date%'";
$today_gp_received_result = mysqli_query($conn, $today_gp_received_sql);
if($today_gp_received_result) {
    $today_gp_received_data = mysqli_fetch_assoc($today_gp_received_result);
    $today_gp_received = ($today_gp_received_data['today_gp_received']) ? $today_gp_received_data['today_gp_received'] : 0;
}

// Today's GP Paid
$today_gp_paid = 0;
$today_gp_paid_sql = "SELECT SUM(amount) as today_gp_paid FROM gp_paid WHERE date_time LIKE '$today_date%'";
$today_gp_paid_result = mysqli_query($conn, $today_gp_paid_sql);
if($today_gp_paid_result) {
    $today_gp_paid_data = mysqli_fetch_assoc($today_gp_paid_result);
    $today_gp_paid = ($today_gp_paid_data['today_gp_paid']) ? $today_gp_paid_data['today_gp_paid'] : 0;
}

// Today's Employee Payments
$today_employee_payments = 0;
$today_employee_payments_sql = "SELECT SUM(amount) as today_payments FROM employee_ledger WHERE entry_type IN ('Salary', 'Advance', 'Bonus') AND date_time LIKE '$today_date%'";
$today_employee_payments_result = mysqli_query($conn, $today_employee_payments_sql);
if($today_employee_payments_result) {
    $today_employee_payments_data = mysqli_fetch_assoc($today_employee_payments_result);
    $today_employee_payments = ($today_employee_payments_data['today_payments']) ? $today_employee_payments_data['today_payments'] : 0;
}

// Today's Employee Recovery
$today_employee_recovery = 0;
$today_employee_recovery_sql = "SELECT SUM(amount) as today_recovery FROM employee_ledger WHERE entry_type = 'Recovery' AND date_time LIKE '$today_date%'";
$today_employee_recovery_result = mysqli_query($conn, $today_employee_recovery_sql);
if($today_employee_recovery_result) {
    $today_employee_recovery_data = mysqli_fetch_assoc($today_employee_recovery_result);
    $today_employee_recovery = ($today_employee_recovery_data['today_recovery']) ? $today_employee_recovery_data['today_recovery'] : 0;
}
?>

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

<div class="cashbook-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-book"></i> Cash Book & Financial Summary</h2>
            <p>Complete financial overview with opening balance, fuel sales, lube sales, employee payments & GP tracking</p>
        </div>
        <div class="header-right">
            <div class="stats-badge">
                <i class="fas fa-calendar"></i>
                <span><?php echo date('d-m-Y H:i'); ?></span>
            </div>
        </div>
    </div>

    <!-- Opening Balance Card -->
    <div class="opening-balance-card mb-4">
        <div class="opening-balance-header">
            <i class="fas fa-chart-line"></i>
            <h5>Opening Balance</h5>
            <button type="button" class="btn-edit-balance" data-bs-toggle="modal" data-bs-target="#openingBalanceModal">
                <i class="fas fa-edit"></i> Edit
            </button>
        </div>
        <div class="opening-balance-body">
            <div class="balance-amount">Rs <?php echo number_format($current_opening_balance, 2); ?></div>
            <div class="balance-note">Starting cash balance for calculations</div>
        </div>
    </div>

    <!-- Main Statistics Cards - Row 1 -->
    <div class="row g-4 mb-4">
        <div class="col-md-6 col-lg-3">
            <div class="stat-card stat-total">
                <div class="stat-icon"><i class="fas fa-chart-line"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_sales_value + $total_lube_cash_sales, 2); ?></h3>
                    <p>Total Cash Sales (Fuel + Lube)</p>
                    <span class="stat-trend"><?php echo number_format($total_liters_sold, 2); ?> Fuel Liters</span>
                </div>
            </div>
        </div>
        <div class="col-md-6 col-lg-3">
            <div class="stat-card stat-credit">
                <div class="stat-icon"><i class="fas fa-shopping-cart"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_credit_sales, 2); ?></h3>
                    <p>Fuel Credit Sales</p>
                    <span class="stat-trend"><?php echo number_format($total_credit_liters, 2); ?> Liters</span>
                </div>
            </div>
        </div>
        <div class="col-md-6 col-lg-3">
            <div class="stat-card stat-cash">
                <div class="stat-icon"><i class="fas fa-money-bill-wave"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_cash_sales, 2); ?></h3>
                    <p>Cash Sales</p>
                    <span class="stat-trend">Fuel: <?php echo number_format($fuel_cash_sales, 2); ?> | Lube: <?php echo number_format($lube_cash_sales, 2); ?></span>
                </div>
            </div>
        </div>
        <div class="col-md-6 col-lg-3">
            <div class="stat-card stat-net">
                <div class="stat-icon"><i class="fas fa-calculator"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($net_cash, 2); ?></h3>
                    <p>Closing Balance</p>
                    <span class="stat-trend">Final Balance</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Row 2 - Expenses, Supplier Payments, Recovery & Advance -->
    <div class="row g-4 mb-4">
        <div class="col-md-3">
            <div class="stat-card stat-expense">
                <div class="stat-icon"><i class="fas fa-file-invoice-dollar"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_expenses, 2); ?></h3>
                    <p>Operating Expenses</p>
                    <span class="stat-trend">Cash Outflow</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card stat-supplier">
                <div class="stat-icon"><i class="fas fa-truck"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_supplier_payments, 2); ?></h3>
                    <p>Supplier Payments</p>
                    <span class="stat-trend">Fuel Supplier Cash Outflow</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card stat-lube-purchase">
                <div class="stat-icon"><i class="fas fa-shopping-cart"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_lube_purchases, 2); ?></h3>
                    <p>Lube Purchases</p>
                    <span class="stat-trend">Lube Supplier Cash Outflow</span>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="stat-card stat-recovery">
                <div class="stat-icon"><i class="fas fa-hand-holding-usd"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_recovery, 2); ?></h3>
                    <p>Customer Recovery</p>
                    <span class="stat-trend">Cash Inflow</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Row 3 - General Party Transactions & Lube Stock & Employee Stats -->
    <div class="row g-4 mb-4">
        <div class="col-md-4">
            <div class="stat-card stat-gp-received">
                <div class="stat-icon"><i class="fas fa-arrow-down"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_gp_received, 2); ?></h3>
                    <p>GP Payment Received</p>
                    <span class="stat-trend">From General Parties (Cash Inflow)</span>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stat-card stat-gp-paid">
                <div class="stat-icon"><i class="fas fa-arrow-up"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_gp_paid, 2); ?></h3>
                    <p>GP Payment Given</p>
                    <span class="stat-trend">To General Parties (Cash Outflow)</span>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="stat-card stat-lube-stock">
                <div class="stat-icon"><i class="fas fa-oil-can"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_lube_stock_value, 2); ?></h3>
                    <p>Lube Stock Value</p>
                    <span class="stat-trend">Current Inventory Value</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Employee Ledger Statistics Cards -->
    <div class="row g-4 mb-4">
        <div class="col-md-6">
            <div class="stat-card" style="border-left-color: #A04657;">
                <div class="stat-icon" style="background: rgba(160,70,87,0.1);">
                    <i class="fas fa-users" style="color: #A04657;"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo $total_employees; ?></h3>
                    <p>Total Employees</p>
                    <span class="stat-trend">Active Staff Members</span>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="stat-card" style="border-left-color: #ff9800;">
                <div class="stat-icon" style="background: rgba(255,152,0,0.1);">
                    <i class="fas fa-rupee-sign" style="color: #ff9800;"></i>
                </div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_employee_outstanding, 2); ?></h3>
                    <p>Employee Outstanding Balance</p>
                    <span class="stat-trend">Total Amount Due from Employees</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Opening Balance Modal -->
    <div class="modal fade" id="openingBalanceModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header-custom">
                    <i class="fas fa-chart-line"></i>
                    <h5 class="modal-title">Update Opening Balance</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST" action="">
                    <div class="modal-body p-4">
                        <div class="current-balance-info mb-3">
                            <label>Current Opening Balance:</label>
                            <strong>Rs <?php echo number_format($current_opening_balance, 2); ?></strong>
                        </div>
                        <div class="input-group-custom mb-3">
                            <label><i class="fas fa-rupee-sign"></i> New Opening Balance <span class="required">*</span></label>
                            <input type="number" step="0.01" name="opening_balance" class="form-control-modern" required 
                                   value="<?php echo $current_opening_balance; ?>" placeholder="Enter opening balance">
                            <small class="input-help">This will be the starting cash balance for all calculations</small>
                        </div>
                        <div class="input-group-custom">
                            <label><i class="fas fa-file-alt"></i> Notes (Optional)</label>
                            <textarea name="notes" class="form-control-modern" rows="2" placeholder="Reason for updating opening balance"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer border-0 pb-4 px-4">
                        <button type="button" class="btn btn-light px-4" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="update_opening_balance" class="btn-update">Update Balance</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Fuel Type Sales Breakdown -->
    <div class="table-card mb-4">
        <div class="table-card-header">
            <div class="header-info">
                <i class="fas fa-oil-can"></i>
                <h4>Fuel Sales Breakdown by Fuel Type</h4>
            </div>
        </div>
        <div class="table-card-body">
            <div class="table-responsive">
                <table class="modern-table">
                    <thead>
                        <tr><th>Fuel Type</th><th>Sale Price (per Liter)</th><th>Total Liters Sold</th><th>Total Sales Value (Rs)</th></td>
                    </thead>
                    <tbody>
                        <?php 
                        $displayed_fuels = 0;
                        if($fuel_breakdown_result && mysqli_num_rows($fuel_breakdown_result) > 0):
                        while($fuel = mysqli_fetch_assoc($fuel_breakdown_result)): 
                            $displayed_fuels++;
                        ?>
                            <tr><td><strong><?php echo htmlspecialchars($fuel['fuel_name']); ?></strong></div>
                                <td>Rs <?php echo number_format($fuel['sale_price'], 2); ?> / L</div>
                                <td><?php echo number_format($fuel['total_liters'], 2); ?> L</div>
                                <td>Rs <?php echo number_format($fuel['total_value'], 2); ?></div>
                            </tr>
                        <?php endwhile; endif; ?>
                        <?php if($displayed_fuels == 0): ?>
                            <tr><td colspan="4" class="text-center">No fuel sales data found</div></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Lube Sales & Purchases Summary -->
    <div class="table-card mb-4">
        <div class="table-card-header">
            <div class="header-info">
                <i class="fas fa-oil-can"></i>
                <h4>Lube Transactions Summary</h4>
            </div>
        </div>
        <div class="table-card-body">
            <div class="table-responsive">
                <table class="modern-table">
                    <thead>
                        <tr><th>Description</th><th>Amount (Rs)</th></tr>
                    </thead>
                    <tbody>
                        <tr class="lube-row">
                            <td><i class="fas fa-shopping-cart"></i> Lube Walk-in Sales (Cash Inflow)</div>
                            <td class="cash-value">+ Rs <?php echo number_format($total_lube_cash_sales, 2); ?></div>
                        </tr>
                        <tr class="lube-credit-row">
                            <td><i class="fas fa-credit-card"></i> Lube Credit Sales (Not in Cashbook)</div>
                            <td class="text-muted">Rs <?php echo number_format($total_lube_credit_sales, 2); ?></div>
                        </tr>
                        <tr class="lube-purchase-row">
                            <td><i class="fas fa-truck"></i> Lube Purchases (Cash Outflow)</div>
                            <td class="minus">- Rs <?php echo number_format($total_lube_purchases, 2); ?></div>
                        </tr>
                        <tr class="lube-stock-row">
                            <td><i class="fas fa-boxes"></i> Lube Inventory Value</div>
                            <td class="lube-stock-value">Rs <?php echo number_format($total_lube_stock_value, 2); ?></div>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Today's Summary Card -->
    <div class="today-card mb-4">
        <div class="today-header">
            <i class="fas fa-sun"></i>
            <h5>Today's Summary</h5>
            <span><?php echo date('l, F j, Y'); ?></span>
        </div>
        <div class="today-body">
            <div class="today-item">
                <span>Today's Fuel Sales:</span>
                <strong><?php echo number_format($today_fuel_liters, 2); ?> Liters</strong>
                <span class="amount">Rs <?php echo number_format($today_fuel_sales_value, 2); ?></span>
            </div>
            <div class="today-item">
                <span>Today's Lube Sales:</span>
                <strong>Walk-in Sales</strong>
                <span class="amount">Rs <?php echo number_format($today_lube_sales_value, 2); ?></span>
            </div>
            <div class="today-item">
                <span>Today's Total Cash Sales:</span>
                <strong>Fuel + Lube</strong>
                <span class="amount" style="color: #A04657;">Rs <?php echo number_format($today_total_sales, 2); ?></span>
            </div>
            <?php if($today_supplier_payments > 0): ?>
            <div class="today-item">
                <span>Today's Fuel Supplier Payments:</span>
                <strong class="text-danger">- Rs <?php echo number_format($today_supplier_payments, 2); ?></strong>
            </div>
            <?php endif; ?>
            <?php if($today_lube_purchases > 0): ?>
            <div class="today-item">
                <span>Today's Lube Purchases:</span>
                <strong class="text-danger">- Rs <?php echo number_format($today_lube_purchases, 2); ?></strong>
            </div>
            <?php endif; ?>
            <?php if($today_advance > 0): ?>
            <div class="today-item">
                <span>Today's Advance Deposits:</span>
                <strong class="text-success">+ Rs <?php echo number_format($today_advance, 2); ?></strong>
            </div>
            <?php endif; ?>
            <?php if($today_gp_received > 0): ?>
            <div class="today-item">
                <span>Today's GP Received:</span>
                <strong class="text-success">+ Rs <?php echo number_format($today_gp_received, 2); ?></strong>
            </div>
            <?php endif; ?>
            <?php if($today_gp_paid > 0): ?>
            <div class="today-item">
                <span>Today's GP Paid:</span>
                <strong class="text-danger">- Rs <?php echo number_format($today_gp_paid, 2); ?></strong>
            </div>
            <?php endif; ?>
            <?php if($today_employee_payments > 0): ?>
            <div class="today-item">
                <span>Today's Employee Payments:</span>
                <strong class="text-danger">- Rs <?php echo number_format($today_employee_payments, 2); ?></strong>
            </div>
            <?php endif; ?>
            <?php if($today_employee_recovery > 0): ?>
            <div class="today-item">
                <span>Today's Employee Recovery:</span>
                <strong class="text-success">+ Rs <?php echo number_format($today_employee_recovery, 2); ?></strong>
            </div>
            <?php endif; ?>
            <div class="today-item">
                <span>Status:</span>
                <strong class="status-active">System Active</strong>
            </div>
        </div>
    </div>

    <!-- Financial Breakdown Table -->
    <div class="table-card mb-4">
        <div class="table-card-header">
            <div class="header-info">
                <i class="fas fa-chart-line"></i>
                <h4>Complete Financial Breakdown</h4>
            </div>
        </div>
        <div class="table-card-body">
            <div class="table-responsive">
                <table class="modern-table">
                    <thead>
                        <tr><th>Description</th><th>Liters</th><th>Amount (Rs)</th><th>Calculation</th></tr>
                    </thead>
                    <tbody>
                        <!-- OPENING BALANCE -->
                        <tr class="opening-balance-row">
                            <td><i class="fas fa-chart-line"></i> <strong>OPENING BALANCE</strong></div>
                            <td>-</div>
                            <td class="opening-value"><strong>Rs <?php echo number_format($current_opening_balance, 2); ?></strong></div>
                            <td>Starting Cash Balance</div>
                        </tr>
                        
                        <!-- Total Fuel Sales -->
                        <tr class="total-row">
                            <td><i class="fas fa-gas-pump"></i> TOTAL FUEL SALES</div>
                            <td><strong><?php echo number_format($total_liters_sold, 2); ?> L</strong></div>
                            <td><strong>Rs <?php echo number_format($total_sales_value, 2); ?></strong></div>
                            <td>From Nozzle Readings × Fuel Sale Prices</div>
                        </tr>
                        
                        <!-- Lube Cash Sales (Walk-in only) -->
                        <tr class="lube-total-row">
                            <td><i class="fas fa-oil-can"></i> LUBE CASH SALES (Walk-in)</div>
                            <td>-</div>
                            <td><strong>Rs <?php echo number_format($total_lube_cash_sales, 2); ?></strong></div>
                            <td>From Lube POS (Walk-in Sales Only)</div>
                        </tr>
                        
                        <tr class="combined-total">
                            <td><i class="fas fa-chart-line"></i> <strong>COMBINED TOTAL SALES</strong></div>
                            <td><strong><?php echo number_format($total_liters_sold, 2); ?> L</strong></div>
                            <td class="cash-value"><strong>Rs <?php echo number_format($total_sales_value + $total_lube_cash_sales, 2); ?></strong></div>
                            <td><strong>Fuel Sales + Lube Cash Sales</strong></div>
                        </tr>
                        
                        <!-- Fuel Credit Sales -->
                        <tr class="credit-row">
                            <td><i class="fas fa-shopping-cart"></i> Less: Fuel Credit Sales</div>
                            <td><?php echo number_format($total_credit_liters, 2); ?> L</div>
                            <td class="minus">- Rs <?php echo number_format($total_credit_sales, 2); ?></div>
                            <td>Manual Credit Entry (Not Cash)</div>
                        </tr>
                        
                        <!-- Total Cash Sales -->
                        <tr class="cash-row">
                            <td><i class="fas fa-money-bill-wave"></i> <strong>= TOTAL CASH SALES</strong></div>
                            <td><strong><?php echo number_format($fuel_cash_liters, 2); ?> L</strong></div>
                            <td class="cash-value"><strong>Rs <?php echo number_format($total_cash_sales, 2); ?></strong></div>
                            <td><strong>Fuel Cash + Lube Cash Sales</strong></div>
                        </tr>
                        
                        <!-- CASH INFLOWS SECTION -->
                        <tr class="section-header">
                            <td colspan="4" style="background: #e8f5e9;"><strong><i class="fas fa-arrow-down"></i> CASH INFLOWS (Money Coming IN)</strong></div>
                        </tr>
                        
                        <!-- Cash Sales -->
                        <tr class="inflow-row">
                            <td><i class="fas fa-money-bill-wave"></i> Cash Sales</div>
                            <td>-</div>
                            <td class="plus">+ Rs <?php echo number_format($total_cash_sales, 2); ?></div>
                            <td>From Fuel & Lube Cash Sales</div>
                        </tr>
                        
                        <!-- Customer Recovery -->
                        <tr class="recovery-row">
                            <td><i class="fas fa-hand-holding-usd"></i> Customer Recovery</div>
                            <td>-</div>
                            <td class="plus">+ Rs <?php echo number_format($total_recovery, 2); ?></div>
                            <td>Payments Received from Customers</div>
                        </tr>
                        
                        <!-- Customer Advance -->
                        <tr class="advance-row">
                            <td><i class="fas fa-money-bill-wave"></i> Customer Advance</div>
                            <td>-</div>
                            <td class="plus advance-value">+ Rs <?php echo number_format($total_advance, 2); ?></div>
                            <td>Advance Deposits from Customers</div>
                        </tr>
                        
                        <!-- GP Received -->
                        <tr class="gp-received-row">
                            <td><i class="fas fa-hand-holding-usd"></i> GP Payment Received</div>
                            <td>-</div>
                            <td class="plus gp-received-value">+ Rs <?php echo number_format($total_gp_received, 2); ?></div>
                            <td>Payments Received from General Parties</div>
                        </tr>
                        
                        <!-- Employee Recovery -->
                        <tr class="employee-recovery-row">
                            <td><i class="fas fa-users"></i> Employee Recovery</div>
                            <td>-</div>
                            <td class="plus" style="color: #20c997;">+ Rs <?php echo number_format($total_employee_recovery, 2); ?></div>
                            <td>Deductions from Employee Balances</div>
                        </tr>
                        
                        <tr class="total-inflow">
                            <td><strong>TOTAL CASH INFLOWS (including Opening Balance)</strong></div>
                            <td>-</div>
                            <td class="cash-value"><strong>Rs <?php echo number_format($total_cash_inflows, 2); ?></strong></div>
                            <td><strong>Opening + Cash Sales + Recovery + Advance + GP Received + Employee Recovery</strong></div>
                        </tr>
                        
                        <!-- CASH OUTFLOWS SECTION -->
                        <tr class="section-header">
                            <td colspan="4" style="background: #ffebee;"><strong><i class="fas fa-arrow-up"></i> CASH OUTFLOWS (Money Going OUT)</strong></div>
                        </tr>
                        
                        <!-- Operating Expenses -->
                        <tr class="expense-row">
                            <td><i class="fas fa-file-invoice-dollar"></i> Operating Expenses</div>
                            <td>-</div>
                            <td class="minus">- Rs <?php echo number_format($total_expenses, 2); ?></div>
                            <td>General Business Expenses</div>
                        </tr>
                        
                        <!-- Supplier Payments -->
                        <tr class="supplier-row">
                            <td><i class="fas fa-truck"></i> Supplier Payments (Fuel)</div>
                            <td>-</div>
                            <td class="minus">- Rs <?php echo number_format($total_supplier_payments, 2); ?></div>
                            <td>Payments to Fuel Suppliers</div>
                        </tr>
                        
                        <!-- Lube Purchases -->
                        <tr class="lube-purchase-row">
                            <td><i class="fas fa-shopping-cart"></i> Lube Purchases</div>
                            <td>-</div>
                            <td class="minus">- Rs <?php echo number_format($total_lube_purchases, 2); ?></div>
                            <td>Lube Stock Purchases (Cash)</div>
                        </tr>
                        
                        <!-- GP Paid -->
                        <tr class="gp-paid-row">
                            <td><i class="fas fa-money-bill-wave"></i> GP Payment Given</div>
                            <td>-</div>
                            <td class="minus">- Rs <?php echo number_format($total_gp_paid, 2); ?></div>
                            <td>Payments Given to General Parties</div>
                        </tr>
                        
                        <!-- Employee Payments -->
                        <tr class="employee-payment-row">
                            <td><i class="fas fa-users"></i> Employee Payments</div>
                            <td>-</div>
                            <td class="minus">- Rs <?php echo number_format($total_employee_payments, 2); ?></div>
                            <td>Salary + Advance + Bonus to Employees</div>
                        </tr>
                        
                        <tr class="total-outflow">
                            <td><strong>TOTAL CASH OUTFLOWS</strong></div>
                            <td>-</div>
                            <td class="minus-value"><strong>- Rs <?php echo number_format($total_cash_outflows, 2); ?></strong></div>
                            <td><strong>Expenses + Supplier Payments + Lube Purchases + GP Paid + Employee Payments</strong></div>
                        </tr>
                        
                        <!-- NET CASH (CLOSING BALANCE) -->
                        <tr class="net-row">
                            <td><i class="fas fa-calculator"></i> <strong>CLOSING BALANCE</strong></div>
                            <td><strong>-</strong></div>
                            <td class="net-value"><strong>Rs <?php echo number_format($net_cash, 2); ?></strong></div>
                            <td><strong>Total Inflows - Total Outflows</strong></div>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- [REST OF THE CODE REMAINS SAME - Activity Cards, Recent Transactions, etc.] -->
    <!-- (Keeping the existing activity cards section as is) -->
    
    <div class="row g-4 mt-2">
        <!-- Nozzle Readings -->
        <div class="col-lg-4">
            <div class="activity-card">
                <div class="activity-header">
                    <i class="fas fa-gas-pump"></i>
                    <h5>Recent Nozzle Readings</h5>
                    <span>Fuel Sales</span>
                </div>
                <div class="activity-body">
                    <div class="table-responsive">
                        <table class="activity-table">
                            <thead>
                                <tr><th width="35%">Nozzle / Fuel</th><th width="20%">Liters</th><th width="25%">Value (Rs)</th><th width="20%">Date</th></tr>
                            </thead>
                            <tbody>
                                <?php 
                                $reading_count = 0;
                                if($nozzle_details_result && mysqli_num_rows($nozzle_details_result) > 0):
                                while($reading = mysqli_fetch_assoc($nozzle_details_result)): 
                                    if($reading_count >= 6) break;
                                    $reading_count++;
                                    $reading_value = $reading['sale_liters'] * $reading['sale_price'];
                                ?>
                                    <tr><td><div class="nozzle-info"><i class="fas fa-oil-can"></i><strong><?php echo htmlspecialchars($reading['nozzle_name']); ?></strong><br><small><?php echo htmlspecialchars($reading['fuel_name']); ?></small></div></div>
                                        <td class="liters-cell"><?php echo number_format($reading['sale_liters'], 2); ?> L</div>
                                        <td class="amount-cell">Rs <?php echo number_format($reading_value, 2); ?></div>
                                        <td class="date-cell"><?php echo date('d-m H:i', strtotime($reading['date_time'])); ?></div>
                                    </tr>
                                <?php endwhile; endif; ?>
                                <?php if($reading_count == 0): ?>
                                    <tr class="empty-row"><td colspan="4"><div class="empty-state-small"><i class="fas fa-gas-pump"></i><p>No nozzle readings found</p></div></div></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Credit Sales (Fuel Only) -->
        <div class="col-lg-4">
            <div class="activity-card">
                <div class="activity-header">
                    <i class="fas fa-shopping-cart"></i>
                    <h5>Recent Fuel Credit Sales</h5>
                    <span>Fuel Credit</span>
                </div>
                <div class="activity-body">
                    <div class="table-responsive">
                        <table class="activity-table">
                            <thead>
                                <tr><th width="35%">Customer</th><th width="25%">Amount (Rs)</th><th width="20%">Liters</th><th width="20%">Date</th><tr>
                            </thead>
                            <tbody>
                                <?php 
                                $credit_count = 0;
                                if($credit_details_result && mysqli_num_rows($credit_details_result) > 0):
                                while($credit = mysqli_fetch_assoc($credit_details_result)): 
                                    if($credit_count >= 6) break;
                                    $credit_count++;
                                ?>
                                    <tr><td><div class="customer-info"><i class="fas fa-user-circle"></i><strong><?php echo htmlspecialchars($credit['customer_name']); ?></strong></div></div>
                                        <td class="amount-cell credit-amount">Rs <?php echo number_format($credit['amount'], 2); ?></div>
                                        <td class="liters-cell"><?php echo number_format($credit['liters'], 2); ?> L</div>
                                        <td class="date-cell"><?php echo date('d-m H:i', strtotime($credit['date_time'])); ?></div>
                                    </tr>
                                <?php endwhile; endif; ?>
                                <?php if($credit_count == 0): ?>
                                    <tr class="empty-row"><td colspan="4"><div class="empty-state-small"><i class="fas fa-shopping-cart"></i><p>No fuel credit sales found</p></div></div></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Employee Ledger Transactions -->
        <div class="col-lg-4">
            <div class="activity-card">
                <div class="activity-header">
                    <i class="fas fa-users"></i>
                    <h5>Employee Ledger Transactions</h5>
                    <span>Recent Activity</span>
                </div>
                <div class="activity-body">
                    <div class="table-responsive">
                        <table class="activity-table">
                            <thead>
                                <tr><th width="30%">Type</th><th width="35%">Employee / Description</th><th width="20%">Amount (Rs)</th><th width="15%">Date</th></tr>
                            </thead>
                            <tbody>
                                <?php 
                                $has_employee_transactions = false;
                                if($recent_employee_entries_result && mysqli_num_rows($recent_employee_entries_result) > 0):
                                while($entry = mysqli_fetch_assoc($recent_employee_entries_result)): 
                                    $has_employee_transactions = true;
                                ?>
                                    <tr>
                                        <td><div class="type-badge <?php 
                                                if($entry['entry_type'] == 'Salary') echo 'lube-sale-badge';
                                                elseif($entry['entry_type'] == 'Advance') echo 'gp-received-badge';
                                                elseif($entry['entry_type'] == 'Bonus') echo 'gp-received-badge';
                                                else echo 'gp-paid-badge';
                                            ?>"><i class="fas <?php 
                                                    if($entry['entry_type'] == 'Salary') echo 'fa-money-bill-wave';
                                                    elseif($entry['entry_type'] == 'Advance') echo 'fa-hand-holding-usd';
                                                    elseif($entry['entry_type'] == 'Bonus') echo 'fa-gift';
                                                    else echo 'fa-undo-alt';
                                                ?>"></i><span><?php echo $entry['entry_type']; ?></span></div></div>
                                        <td><div class="party-info"><i class="fas fa-user-tie"></i><strong><?php echo htmlspecialchars($entry['employee_name']); ?></strong><br><small><?php echo htmlspecialchars(substr($entry['description'], 0, 25) ?: '—'); ?></small></div></div>
                                        <td class="amount-cell <?php echo ($entry['entry_type'] != 'Recovery') ? 'outflow-amount' : 'inflow-amount'; ?>"><?php echo ($entry['entry_type'] != 'Recovery') ? '-' : '+'; ?> Rs <?php echo number_format($entry['amount'], 2); ?></div>
                                        <td class="date-cell"><?php echo date('d-m H:i', strtotime($entry['date_time'])); ?></div>
                                    </tr>
                                <?php endwhile; endif; ?>
                                <?php if(!$has_employee_transactions): ?>
                                    <tr class="empty-row"><td colspan="4"><div class="empty-state-small"><i class="fas fa-users"></i><p>No employee transactions found</p><small>Add employee ledger entries</small></div></div></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Lube Sales & GP Transactions Row -->
    <div class="row g-4 mt-2">
        <!-- Lube Cash Sales Details -->
        <div class="col-lg-6">
            <div class="activity-card">
                <div class="activity-header">
                    <i class="fas fa-oil-can"></i>
                    <h5>Recent Lube Cash Sales</h5>
                    <span>Walk-in Sales (Cash Inflow)</span>
                </div>
                <div class="activity-body">
                    <div class="table-responsive">
                        <table class="activity-table">
                            <thead>
                                <tr><th width="30%">Invoice</th><th width="35%">Amount (Rs)</th><th width="20%">Status</th><th width="15%">Date</th></tr>
                            </thead>
                            <tbody>
                                <?php 
                                $lube_count = 0;
                                if($lube_sales_details_result && mysqli_num_rows($lube_sales_details_result) > 0):
                                while($lube = mysqli_fetch_assoc($lube_sales_details_result)): 
                                    if($lube_count >= 6) break;
                                    $lube_count++;
                                ?>
                                    <tr>
                                        <td><div class="invoice-info"><i class="fas fa-receipt"></i><strong><?php echo htmlspecialchars($lube['sale_invoice']); ?></strong></div></div>
                                        <td class="amount-cell inflow-amount">Rs <?php echo number_format($lube['total_amount'], 2); ?></div>
                                        <td><span class="badge-inflow">Completed</span></div>
                                        <td class="date-cell"><?php echo date('d-m H:i', strtotime($lube['sale_date'])); ?></div>
                                    </tr>
                                <?php endwhile; endif; ?>
                                <?php if($lube_count == 0): ?>
                                    <tr class="empty-row"><td colspan="4"><div class="empty-state-small"><i class="fas fa-oil-can"></i><p>No lube cash sales found</p></div></div></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- GP Transactions -->
        <div class="col-lg-6">
            <div class="activity-card">
                <div class="activity-header">
                    <i class="fas fa-exchange-alt"></i>
                    <h5>GP Transactions</h5>
                    <span>General Party Activity</span>
                </div>
                <div class="activity-body">
                    <div class="table-responsive">
                        <table class="activity-table">
                            <thead>
                                <tr><th width="25%">Type</th><th width="40%">Party / Description</th><th width="20%">Amount (Rs)</th><th width="15%">Date</th></tr>
                            </thead>
                            <tbody>
                                <?php 
                                $has_gp_transactions = false;
                                
                                if($gp_received_details_result && mysqli_num_rows($gp_received_details_result) > 0):
                                while($payment = mysqli_fetch_assoc($gp_received_details_result)): 
                                    $has_gp_transactions = true;
                                ?>
                                    <tr class="gp-received-row">
                                        <td><div class="type-badge gp-received-badge"><i class="fas fa-hand-holding-usd"></i><span>Received</span></div></div>
                                        <td><div class="party-info"><i class="fas fa-building"></i><strong><?php echo htmlspecialchars($payment['gp_name']); ?></strong><br><small><?php echo htmlspecialchars(substr($payment['description'], 0, 30)); ?></small></div></div>
                                        <td class="amount-cell inflow-amount">+ Rs <?php echo number_format($payment['amount'], 2); ?></div>
                                        <td class="date-cell"><?php echo date('d-m H:i', strtotime($payment['date_time'])); ?></div>
                                    </tr>
                                <?php endwhile; endif; ?>
                                
                                <?php 
                                if($gp_paid_details_result && mysqli_num_rows($gp_paid_details_result) > 0):
                                while($payment = mysqli_fetch_assoc($gp_paid_details_result)): 
                                    $has_gp_transactions = true;
                                ?>
                                    <tr class="gp-paid-row">
                                        <td><div class="type-badge gp-paid-badge"><i class="fas fa-hand-holding-usd"></i><span>Paid</span></div></div>
                                        <td><div class="party-info"><i class="fas fa-building"></i><strong><?php echo htmlspecialchars($payment['gp_name']); ?></strong><br><small><?php echo htmlspecialchars(substr($payment['description'], 0, 30)); ?></small></div></div>
                                        <td class="amount-cell outflow-amount">- Rs <?php echo number_format($payment['amount'], 2); ?></div>
                                        <td class="date-cell"><?php echo date('d-m H:i', strtotime($payment['date_time'])); ?></div>
                                    </tr>
                                <?php endwhile; endif; ?>
                                
                                <?php if(!$has_gp_transactions): ?>
                                    <tr class="empty-row"><td colspan="4"><div class="empty-state-small"><i class="fas fa-exchange-alt"></i><p>No GP transactions found</p></div></div></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Lube Purchases Details Section -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="activity-card">
                <div class="activity-header">
                    <i class="fas fa-shopping-cart"></i>
                    <h5>Recent Lube Purchases (Cash Payments)</h5>
                    <span>Supplier Payments for Lube Stock</span>
                </div>
                <div class="activity-body">
                    <div class="table-responsive">
                        <table class="activity-table">
                            <thead>
                                <tr><th>Invoice</th><th>Supplier</th><th>Amount</th><th>Date</th></tr>
                            </thead>
                            <tbody>
                                <?php 
                                $lube_purchase_count = 0;
                                if($lube_purchases_details_result && mysqli_num_rows($lube_purchases_details_result) > 0):
                                while($purchase = mysqli_fetch_assoc($lube_purchases_details_result)): 
                                    if($lube_purchase_count >= 5) break;
                                    $lube_purchase_count++;
                                ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($purchase['purchase_invoice']); ?></div>
                                        <td><?php echo htmlspecialchars($purchase['supplier_name']); ?></div>
                                        <td class="minus">- Rs <?php echo number_format($purchase['total_amount'], 2); ?></div>
                                        <td><?php echo date('d-m H:i', strtotime($purchase['purchase_date'])); ?></div>
                                    </tr>
                                <?php endwhile; endif; ?>
                                <?php if($lube_purchase_count == 0): ?>
                                    <td><td colspan="4" class="text-center">No lube purchase records found</div></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Expenses Details Section -->
    <div class="row mt-4">
        <div class="col-12">
            <div class="activity-card">
                <div class="activity-header">
                    <i class="fas fa-file-invoice-dollar"></i>
                    <h5>Recent Expenses</h5>
                    <span>Operating Costs</span>
                </div>
                <div class="activity-body">
                    <div class="table-responsive">
                        <table class="activity-table">
                            <thead>
                                <td><th>Title</th><th>Category</th><th>Amount</th><th>Date</th></tr>
                            </thead>
                            <tbody>
                                <?php 
                                $exp_count = 0;
                                if($expenses_details_result && mysqli_num_rows($expenses_details_result) > 0):
                                while($exp = mysqli_fetch_assoc($expenses_details_result)): 
                                    if($exp_count >= 5) break;
                                    $exp_count++;
                                    $exp_amount = ($exp['amount']) ? $exp['amount'] : $exp['expense_amount'];
                                ?>
                                    <tr>
                                        <td><?php echo htmlspecialchars($exp['title']); ?></div>
                                        <td><?php echo htmlspecialchars($exp['category']); ?></div>
                                        <td class="minus">- Rs <?php echo number_format($exp_amount, 2); ?></div>
                                        <td><?php echo date('d-m H:i', strtotime($exp['date_time'])); ?></div>
                                    </tr>
                                <?php endwhile; endif; ?>
                                <?php if($exp_count == 0): ?>
                                    <tr><td colspan="4" class="text-center">No expenses recorded</div></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
/* [SAME CSS AS BEFORE - Keeping all existing styles] */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');

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

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

.cashbook-container {
    padding: 0;
}

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

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

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

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

/* Opening Balance Card */
.opening-balance-card {
    background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
    border-radius: 20px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    border-left: 4px solid #0284c7;
}

.opening-balance-header {
    background: #0284c7;
    padding: 12px 20px;
    display: flex;
    align-items: center;
    gap: 10px;
    color: #fff;
}

.opening-balance-header i { font-size: 18px; }
.opening-balance-header h5 { margin: 0; font-size: 15px; color: #fff; }
.opening-balance-header .btn-edit-balance {
    margin-left: auto;
    background: rgba(255,255,255,0.2);
    border: none;
    color: #fff;
    padding: 5px 12px;
    border-radius: 20px;
    font-size: 11px;
    cursor: pointer;
    transition: all 0.3s;
}

.opening-balance-header .btn-edit-balance:hover {
    background: rgba(255,255,255,0.3);
}

.opening-balance-body {
    padding: 20px;
    text-align: center;
}

.opening-balance-body .balance-amount {
    font-size: 32px;
    font-weight: 800;
    color: #0284c7;
}

.opening-balance-body .balance-note {
    font-size: 11px;
    color: #666;
    margin-top: 5px;
}

/* Stat 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;
}

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

.stat-total { border-left: 4px solid #A04657; }
.stat-credit { border-left: 4px solid #dc3545; }
.stat-cash { border-left: 4px solid #28a745; }
.stat-net { border-left: 4px solid #17a2b8; }
.stat-expense { border-left: 4px solid #fd7e14; }
.stat-supplier { border-left: 4px solid #6c5ce7; }
.stat-lube-purchase { border-left: 4px solid #ff9800; }
.stat-recovery { border-left: 4px solid #20c997; }
.stat-advance { border-left: 4px solid #17a2b8; }
.stat-gp-received { border-left: 4px solid #28a745; }
.stat-gp-paid { border-left: 4px solid #dc3545; }
.stat-lube-stock { border-left: 4px solid #ff9800; }

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

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

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

.stat-info p {
    margin: 3px 0 0;
    color: #666;
    font-size: 12px;
    font-weight: 500;
}

.stat-trend {
    font-size: 10px;
    color: #999;
}

/* Modal */
.modal-header-custom {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    padding: 15px 20px;
    color: #fff;
    border-radius: 12px 12px 0 0;
    display: flex;
    align-items: center;
    gap: 10px;
}

.modal-header-custom .modal-title {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
}

.current-balance-info {
    background: #e3f2fd;
    padding: 12px;
    border-radius: 10px;
    display: flex;
    justify-content: space-between;
    font-size: 13px;
}

.btn-update {
    background: #A04657;
    color: #fff;
    border: none;
    padding: 8px 25px;
    border-radius: 25px;
    font-weight: 600;
    transition: all 0.3s;
}

.btn-update:hover {
    background: #6b2a36;
    transform: translateY(-2px);
}

/* Today Card */
.today-card {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 16px;
    overflow: hidden;
}

.today-header {
    background: #A04657;
    padding: 12px 20px;
    display: flex;
    align-items: center;
    gap: 12px;
    color: #fff;
}

.today-header i { font-size: 18px; }
.today-header h5 { margin: 0; font-size: 15px; color: #fff; }
.today-header span { margin-left: auto; font-size: 12px; opacity: 0.9; }

.today-body {
    padding: 15px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    flex-wrap: wrap;
    gap: 15px;
}

.today-item {
    display: flex;
    align-items: baseline;
    gap: 10px;
}

.today-item span { font-size: 13px; color: #666; }
.today-item strong { font-size: 16px; font-weight: 600; color: #333; }
.today-item .amount { font-size: 18px; font-weight: bold; color: #28a745; }
.text-danger { color: #dc3545 !important; font-size: 16px; }
.text-success { color: #28a745 !important; }
.status-active { color: #28a745; font-weight: 600; }

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

.table-card-header {
    padding: 18px 20px;
    border-bottom: 1px solid #f0f0f0;
}

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

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

.modern-table th {
    padding: 12px 15px;
    background: #f8f9fa;
    font-weight: 600;
    color: #555;
    font-size: 12px;
    text-align: left;
}

.modern-table td {
    padding: 12px 15px;
    border-bottom: 1px solid #f0f0f0;
    font-size: 13px;
    color: #444;
}

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

.section-header td {
    background: #e8f5e9;
    font-weight: 600;
    padding: 10px 15px;
}

.opening-balance-row td { background: #e0f2fe; font-weight: 600; }
.opening-value { color: #0284c7; font-size: 16px; font-weight: bold; }
.total-row td, .cash-row td, .net-row td, .total-inflow td, .total-outflow td, .combined-total td { font-weight: 600; background: #fafafa; }
.lube-total-row td, .lube-credit-row td, .lube-stock-row td, .lube-purchase-row td { background: #fff8e1; }
.combined-total td { background: #e3f2fd; }
.minus { color: #dc3545; font-weight: 500; }
.plus { color: #28a745; font-weight: 500; }
.advance-value { color: #17a2b8; font-weight: 500; }
.gp-received-value { color: #28a745; font-weight: 500; }
.lube-stock-value { color: #ff9800; font-weight: 500; }
.cash-value { color: #28a745; font-size: 16px; }
.minus-value { color: #dc3545; font-size: 16px; }
.net-value { color: #A04657; font-size: 18px; font-weight: bold; }

/* Activity Cards */
.activity-card {
    background: #fff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    height: 100%;
}

.activity-header {
    padding: 15px 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    align-items: center;
    gap: 10px;
}

.activity-header i { font-size: 18px; color: #A04657; }
.activity-header h5 { margin: 0; font-size: 15px; }
.activity-header span { margin-left: auto; font-size: 11px; color: #999; }

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

.activity-table th {
    padding: 10px 15px;
    background: #fafafa;
    font-size: 11px;
    font-weight: 600;
    color: #666;
    text-align: left;
}

.activity-table td {
    padding: 10px 15px;
    border-bottom: 1px solid #f5f5f5;
    font-size: 12px;
}

/* Badges */
.badge-outflow {
    background: #ffebee;
    color: #dc3545;
    padding: 3px 8px;
    border-radius: 12px;
    font-size: 10px;
    font-weight: 600;
    display: inline-block;
}

.badge-inflow {
    background: #e8f5e9;
    color: #28a745;
    padding: 3px 8px;
    border-radius: 12px;
    font-size: 10px;
    font-weight: 600;
    display: inline-block;
}

.type-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 12px;
    border-radius: 20px;
    font-size: 11px;
    font-weight: 600;
    white-space: nowrap;
}

.lube-sale-badge {
    background: #e8f5e9;
    color: #2e7d32;
}

.gp-received-badge {
    background: #e3f2fd;
    color: #1565c0;
}

.gp-paid-badge {
    background: #ffebee;
    color: #c62828;
}

/* Party Info */
.party-info i,
.nozzle-info i,
.customer-info i,
.invoice-info i {
    color: #A04657;
    margin-right: 6px;
}

.party-info strong,
.nozzle-info strong,
.customer-info strong,
.invoice-info strong {
    font-size: 13px;
    color: #1a1a2e;
}

.party-info small,
.nozzle-info small {
    font-size: 10px;
    color: #999;
    display: block;
    margin-top: 2px;
}

/* Amount Cells */
.amount-cell {
    font-weight: 700;
    font-size: 13px;
}

.inflow-amount {
    color: #28a745;
}

.outflow-amount {
    color: #dc3545;
}

.credit-amount {
    color: #dc3545;
    font-weight: 600;
}

.liters-cell {
    font-weight: 600;
    color: #17a2b8;
}

.date-cell {
    font-size: 11px;
    color: #888;
}

/* Empty State */
.empty-state-small {
    text-align: center;
    padding: 30px 20px;
}

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

.empty-state-small p {
    font-size: 13px;
    color: #999;
    margin: 0;
}

/* Responsive */
@media (max-width: 768px) {
    .page-header { flex-direction: column; text-align: center; gap: 15px; }
    .today-body { flex-direction: column; text-align: center; }
    .modern-table th, .modern-table td { font-size: 11px; padding: 8px 10px; }
    .opening-balance-body .balance-amount { font-size: 24px; }
}

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

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