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

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

$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');

// ============================================
// OPENING BALANCE (Before from_date)
// ============================================

// Get cash sales before from_date
$opening_cash_sales_sql = "SELECT COALESCE(SUM(nr.sale_liters * ft.sale_price), 0) as total
                           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 DATE(nr.date_time) < '$from_date'";
$opening_cash_sales_result = mysqli_query($conn, $opening_cash_sales_sql);
$opening_cash_sales_data = mysqli_fetch_assoc($opening_cash_sales_result);
$opening_cash_sales = $opening_cash_sales_data['total'] ?? 0;

// Get credit sales before from_date (these are not cash, so subtract)
$opening_credit_sales_sql = "SELECT COALESCE(SUM(amount), 0) as total
                             FROM credit_sales 
                             WHERE DATE(date_time) < '$from_date'";
$opening_credit_sales_result = mysqli_query($conn, $opening_credit_sales_sql);
$opening_credit_sales_data = mysqli_fetch_assoc($opening_credit_sales_result);
$opening_credit_sales = $opening_credit_sales_data['total'] ?? 0;

// Get customer payments before from_date
$opening_payments_sql = "SELECT COALESCE(SUM(amount), 0) as total
                         FROM customer_payments 
                         WHERE payment_type = 'payment' 
                         AND DATE(date_time) < '$from_date'";
$opening_payments_result = mysqli_query($conn, $opening_payments_sql);
$opening_payments_data = mysqli_fetch_assoc($opening_payments_result);
$opening_payments = $opening_payments_data['total'] ?? 0;

// Get advance deposits before from_date
$opening_advance_sql = "SELECT COALESCE(SUM(amount), 0) as total
                        FROM customer_payments 
                        WHERE payment_type = 'advance' 
                        AND DATE(date_time) < '$from_date'";
$opening_advance_result = mysqli_query($conn, $opening_advance_sql);
$opening_advance_data = mysqli_fetch_assoc($opening_advance_result);
$opening_advance = $opening_advance_data['total'] ?? 0;

// Get expenses before from_date
$opening_expenses_sql = "SELECT COALESCE(SUM(COALESCE(amount, expense_amount)), 0) as total
                         FROM expenses 
                         WHERE DATE(date_time) < '$from_date'";
$opening_expenses_result = mysqli_query($conn, $opening_expenses_sql);
$opening_expenses_data = mysqli_fetch_assoc($opening_expenses_result);
$opening_expenses = $opening_expenses_data['total'] ?? 0;

// Get supplier payments before from_date
$opening_supplier_payments_sql = "SELECT COALESCE(SUM(amount), 0) as total
                                  FROM supplier_payments 
                                  WHERE DATE(date_time) < '$from_date'";
$opening_supplier_payments_result = mysqli_query($conn, $opening_supplier_payments_sql);
$opening_supplier_payments_data = mysqli_fetch_assoc($opening_supplier_payments_result);
$opening_supplier_payments = $opening_supplier_payments_data['total'] ?? 0;

// Get GP received before from_date
$opening_gp_received_sql = "SELECT COALESCE(SUM(amount), 0) as total
                            FROM gp_received 
                            WHERE DATE(date_time) < '$from_date'";
$opening_gp_received_result = mysqli_query($conn, $opening_gp_received_sql);
$opening_gp_received_data = mysqli_fetch_assoc($opening_gp_received_result);
$opening_gp_received = $opening_gp_received_data['total'] ?? 0;

// Get GP paid before from_date
$opening_gp_paid_sql = "SELECT COALESCE(SUM(amount), 0) as total
                        FROM gp_paid 
                        WHERE DATE(date_time) < '$from_date'";
$opening_gp_paid_result = mysqli_query($conn, $opening_gp_paid_sql);
$opening_gp_paid_data = mysqli_fetch_assoc($opening_gp_paid_result);
$opening_gp_paid = $opening_gp_paid_data['total'] ?? 0;

// Calculate opening balance (Cash in hand at start)
$opening_balance = ($opening_cash_sales - $opening_credit_sales) + $opening_payments + $opening_advance + $opening_gp_received - $opening_expenses - $opening_supplier_payments - $opening_gp_paid;

if($opening_balance < 0) $opening_balance = 0;

// ============================================
// CASH INFLOWS (During selected period)
// ============================================

// 1. Cash Sales (from nozzle_readings)
$cash_sales_sql = "SELECT COALESCE(SUM(nr.sale_liters * ft.sale_price), 0) as amount
                   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 DATE(nr.date_time) BETWEEN '$from_date' AND '$to_date'";
$cash_sales_result = mysqli_query($conn, $cash_sales_sql);
$cash_sales_data = mysqli_fetch_assoc($cash_sales_result);
$cash_sales = $cash_sales_data['amount'] ?? 0;

// 2. Credit Sales during period (not cash, so subtract from total sales)
$credit_sales_sql = "SELECT COALESCE(SUM(amount), 0) as amount
                     FROM credit_sales 
                     WHERE DATE(date_time) BETWEEN '$from_date' AND '$to_date'";
$credit_sales_result = mysqli_query($conn, $credit_sales_sql);
$credit_sales_data = mysqli_fetch_assoc($credit_sales_result);
$credit_sales = $credit_sales_data['amount'] ?? 0;

// Net Cash Sales
$net_cash_sales = $cash_sales - $credit_sales;
if($net_cash_sales < 0) $net_cash_sales = 0;

// 3. Customer Payments (Recovery)
$recovery_sql = "SELECT COALESCE(SUM(amount), 0) as amount 
                 FROM customer_payments 
                 WHERE payment_type = 'payment' 
                 AND DATE(date_time) BETWEEN '$from_date' AND '$to_date'";
$recovery_result = mysqli_query($conn, $recovery_sql);
$recovery_data = mysqli_fetch_assoc($recovery_result);
$customer_recovery = $recovery_data['amount'] ?? 0;

// 4. Customer Advance Deposits
$advance_sql = "SELECT COALESCE(SUM(amount), 0) as amount 
                FROM customer_payments 
                WHERE payment_type = 'advance' 
                AND DATE(date_time) BETWEEN '$from_date' AND '$to_date'";
$advance_result = mysqli_query($conn, $advance_sql);
$advance_data = mysqli_fetch_assoc($advance_result);
$customer_advance = $advance_data['amount'] ?? 0;

// 5. GP Received (Party paid us)
$gp_received_sql = "SELECT COALESCE(SUM(amount), 0) as amount 
                    FROM gp_received 
                    WHERE DATE(date_time) BETWEEN '$from_date' AND '$to_date'";
$gp_received_result = mysqli_query($conn, $gp_received_sql);
$gp_received_data = mysqli_fetch_assoc($gp_received_result);
$gp_received = $gp_received_data['amount'] ?? 0;

// Total Cash Inflows
$total_inflows = $net_cash_sales + $customer_recovery + $customer_advance + $gp_received;

// ============================================
// CASH OUTFLOWS (During selected period)
// ============================================

// 1. Operating Expenses
$expenses_sql = "SELECT COALESCE(SUM(COALESCE(amount, expense_amount)), 0) as amount 
                 FROM expenses 
                 WHERE DATE(date_time) BETWEEN '$from_date' AND '$to_date'";
$expenses_result = mysqli_query($conn, $expenses_sql);
$expenses_data = mysqli_fetch_assoc($expenses_result);
$expenses = $expenses_data['amount'] ?? 0;

// 2. Supplier Payments
$supplier_payments_sql = "SELECT COALESCE(SUM(amount), 0) as amount 
                          FROM supplier_payments 
                          WHERE DATE(date_time) BETWEEN '$from_date' AND '$to_date'";
$supplier_payments_result = mysqli_query($conn, $supplier_payments_sql);
$supplier_payments_data = mysqli_fetch_assoc($supplier_payments_result);
$supplier_payments = $supplier_payments_data['amount'] ?? 0;

// 3. GP Paid (We paid to party)
$gp_paid_sql = "SELECT COALESCE(SUM(amount), 0) as amount 
                FROM gp_paid 
                WHERE DATE(date_time) BETWEEN '$from_date' AND '$to_date'";
$gp_paid_result = mysqli_query($conn, $gp_paid_sql);
$gp_paid_data = mysqli_fetch_assoc($gp_paid_result);
$gp_paid = $gp_paid_data['amount'] ?? 0;

// Total Cash Outflows
$total_outflows = $expenses + $supplier_payments + $gp_paid;

// ============================================
// CLOSING BALANCE
// ============================================
$closing_balance = $opening_balance + $total_inflows - $total_outflows;

// ============================================
// GET DETAILED TRANSACTIONS
// ============================================
$transactions = [];

// Cash Sales from nozzle readings
$sales_details_sql = "SELECT nr.date_time, 'Cash Sale' as type, (nr.sale_liters * ft.sale_price) as amount, 
                             CONCAT(ft.name, ' - ', nr.sale_liters, ' L') as description
                      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 DATE(nr.date_time) BETWEEN '$from_date' AND '$to_date'
                      ORDER BY nr.date_time DESC LIMIT 15";
$sales_details = mysqli_query($conn, $sales_details_sql);
while($row = mysqli_fetch_assoc($sales_details)) {
    $row['amount'] = floatval($row['amount']);
    $transactions[] = $row;
}

// Customer Payments
$payment_details_sql = "SELECT cp.date_time, 
                               CASE WHEN cp.payment_type = 'payment' THEN 'Payment Received' ELSE 'Advance Deposit' END as type, 
                               cp.amount, 
                               CONCAT(c.name, IFNULL(CONCAT(' - ', cp.notes), '')) as description
                        FROM customer_payments cp
                        LEFT JOIN customers c ON cp.customer_id = c.id
                        WHERE cp.payment_type IN ('payment', 'advance')
                        AND DATE(cp.date_time) BETWEEN '$from_date' AND '$to_date'
                        ORDER BY cp.date_time DESC LIMIT 10";
$payment_details = mysqli_query($conn, $payment_details_sql);
while($row = mysqli_fetch_assoc($payment_details)) {
    $row['amount'] = floatval($row['amount']);
    $transactions[] = $row;
}

// Supplier Payments
$supplier_details_sql = "SELECT sp.date_time, 'Supplier Payment' as type, sp.amount, 
                                CONCAT(s.name, IFNULL(CONCAT(' - ', sp.notes), '')) as description
                         FROM supplier_payments sp
                         LEFT JOIN suppliers s ON sp.supplier_id = s.id
                         WHERE DATE(sp.date_time) BETWEEN '$from_date' AND '$to_date'
                         ORDER BY sp.date_time DESC LIMIT 10";
$supplier_details = mysqli_query($conn, $supplier_details_sql);
while($row = mysqli_fetch_assoc($supplier_details)) {
    $row['amount'] = floatval($row['amount']);
    $transactions[] = $row;
}

// Expenses
$expense_details_sql = "SELECT date_time, 'Expense' as type, 
                               COALESCE(amount, expense_amount) as amount, 
                               CONCAT(title, IFNULL(CONCAT(' - ', description), '')) as description
                        FROM expenses 
                        WHERE DATE(date_time) BETWEEN '$from_date' AND '$to_date'
                        ORDER BY date_time DESC LIMIT 10";
$expense_details = mysqli_query($conn, $expense_details_sql);
while($row = mysqli_fetch_assoc($expense_details)) {
    $row['amount'] = floatval($row['amount']);
    $transactions[] = $row;
}

// Sort transactions by date (newest first)
usort($transactions, function($a, $b) {
    return strtotime($b['date_time']) - strtotime($a['date_time']);
});
?>

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cash Book Closing Report</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- PDF Generation Libraries -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <style>
        /* Cash Book Closing Report Styles - FULL WIDTH, NO EXTRA SPACING */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=Quicksand:wght@400;500;600;700&family=Poppins:wght@300;400;500;600;700&display=swap');

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

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

h1, h2, h3, h4, h5, h6,
.page-header h2,
.header-info h4 {
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}

/* Main Content - FULL WIDTH, MINIMAL PADDING */
.main-content {
    margin-left: 280px;
    padding: 15px 20px;
    transition: all 0.3s;
    width: calc(100% - 280px);
    background: #f5f7fb;
}

.cashbook-closing-container {
    max-width: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}

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

.page-header h2 {
    margin: 0 0 4px 0;
    font-size: 22px;
}

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

.btn-pdf-header {
    background: #dc3545;
    color: #fff;
    padding: 6px 18px;
    border-radius: 40px;
    border: none;
    font-weight: 600;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.3s;
    font-size: 12px;
}

.btn-pdf-header:hover {
    background: #c82333;
}

/* Summary Cards - COMPACT GRID */
.summary-cards {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 16px;
    margin-bottom: 20px;
    width: 100%;
}

.summary-card {
    background: #fff;
    border-radius: 16px;
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 14px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    transition: all 0.3s;
    border: 1px solid #f0f0f0;
}

.summary-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 8px 18px rgba(160,70,87,0.1);
}

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

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

.opening-icon { background: rgba(23,162,184,0.1); }
.opening-icon i { color: #17a2b8; }
.inflow-icon { background: rgba(40,167,69,0.1); }
.inflow-icon i { color: #28a745; }
.outflow-icon { background: rgba(220,53,69,0.1); }
.outflow-icon i { color: #dc3545; }
.closing-icon { background: rgba(160,70,87,0.1); }
.closing-icon i { color: #A04657; }

.summary-content h4 {
    margin: 0;
    font-size: 20px;
    font-weight: 800;
}

.summary-content p {
    margin: 3px 0 0;
    font-size: 11px;
    color: #666;
}

.summary-content small {
    font-size: 9px;
    color: #999;
    display: block;
    margin-top: 2px;
}

.text-success { color: #28a745; }
.text-danger { color: #dc3545; }

/* Filter Card - COMPACT */
.filter-card {
    background: #fff;
    border-radius: 16px;
    margin-bottom: 20px;
    overflow: hidden;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    border: 1px solid #f0f0f0;
    width: 100%;
}

.filter-header {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    padding: 10px 20px;
    color: #fff;
    font-weight: 600;
    font-size: 13px;
}

.filter-body {
    padding: 16px;
}

.filter-row {
    display: flex;
    flex-wrap: wrap;
    gap: 12px;
    align-items: flex-end;
}

.filter-group {
    flex: 1;
    min-width: 160px;
}

.filter-group label {
    display: block;
    font-size: 10px;
    font-weight: 600;
    text-transform: uppercase;
    color: #666;
    margin-bottom: 4px;
}

.form-control-modern {
    width: 100%;
    padding: 8px 12px;
    border: 1.5px solid #e8e8e8;
    border-radius: 10px;
    font-size: 12px;
    background: #fafafa;
}

.form-control-modern:focus {
    border-color: #A04657;
    outline: none;
}

.filter-actions {
    display: flex;
    gap: 8px;
}

.btn-search, .btn-reset, .btn-pdf {
    padding: 8px 18px;
    border-radius: 10px;
    font-weight: 600;
    font-size: 12px;
    cursor: pointer;
    border: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.3s;
}

.btn-search {
    background: linear-gradient(135deg, #A04657, #6b2a36);
    color: #fff;
}

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

.btn-reset {
    background: #f0f0f0;
    color: #555;
    text-decoration: none;
}

.btn-reset:hover {
    background: #e0e0e0;
}

.btn-pdf {
    background: #dc3545;
    color: #fff;
}

.btn-pdf:hover {
    background: #c82333;
}

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

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

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

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

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

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

/* Cashflow Table */
.cashflow-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    min-width: 800px;
}

.cashflow-table th, .cashflow-table td {
    padding: 10px 12px;
    border-bottom: 1px solid #f0f0f0;
}

.cashflow-table th {
    background: #f8f9fc;
    font-weight: 700;
    color: #445566;
    font-size: 11px;
    text-transform: uppercase;
}

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

.opening-row {
    background: #f8f9fc;
    font-weight: 600;
}

.section-header td {
    background: #e9ecef;
    font-weight: 600;
    padding: 8px 12px;
    font-size: 12px;
}

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

.net-row {
    background: #fff8e1;
    font-weight: 700;
}

.closing-row {
    background: #e8f5e9;
    font-weight: 700;
}

.trans-badge {
    display: inline-block;
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 600;
}

.trans-badge.inflow {
    background: #e8f5e9;
    color: #2e7d32;
}

.trans-badge.outflow {
    background: #ffebee;
    color: #c62828;
}

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

.modern-table th {
    padding: 10px 12px;
    background: #f8f9fc;
    font-weight: 700;
    color: #445566;
    font-size: 11px;
    border-bottom: 1px solid #e8e8e8;
}

.modern-table td {
    padding: 8px 12px;
    border-bottom: 1px solid #f0f0f0;
    font-size: 12px;
    font-weight: 500;
}

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

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

.empty-state p {
    font-size: 13px;
    font-weight: 500;
}

/* Sidebar Styles */
.sidebar {
    width: 280px;
    background: #1a1a2e;
    color: #fff;
    transition: all 0.3s;
    position: fixed;
    height: 100vh;
    overflow-y: auto;
    z-index: 1000;
}

.sidebar-header {
    padding: 25px 20px;
    border-bottom: 1px solid rgba(255,255,255,0.1);
    text-align: center;
}

.sidebar-header h3 {
    color: #fff;
    font-size: 1.5rem;
    margin: 0;
}

.sidebar-header p {
    color: rgba(255,255,255,0.7);
    font-size: 0.75rem;
    margin: 5px 0 0;
}

.sidebar-nav {
    padding: 20px 0;
}

.nav-item {
    list-style: none;
}

.nav-link-custom {
    display: flex;
    align-items: center;
    padding: 12px 25px;
    color: rgba(255,255,255,0.8);
    text-decoration: none;
    transition: all 0.3s;
    gap: 12px;
    font-size: 0.9rem;
}

.nav-link-custom:hover, .nav-link-custom.active {
    background: rgba(160,70,87,0.3);
    color: #fff;
    border-left: 3px solid #A04657;
}

.nav-link-custom i {
    width: 22px;
    font-size: 1.1rem;
}

/* Top Header */
.top-header {
    background: #fff;
    border-radius: 16px;
    padding: 12px 20px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    width: 100%;
}

.welcome-text h4 {
    margin: 0;
    font-size: 1.1rem;
    color: #333;
}

.welcome-text p {
    margin: 0;
    font-size: 0.75rem;
    color: #777;
}

.user-info {
    display: flex;
    align-items: center;
    gap: 20px;
}

.logout-btn {
    background: #A04657;
    color: #fff;
    padding: 6px 18px;
    border-radius: 30px;
    text-decoration: none;
    font-size: 0.8rem;
    transition: all 0.3s;
}

.logout-btn:hover {
    background: #6b2a36;
    color: #fff;
}

/* Footer */
.footer {
    background: #fff;
    border-radius: 12px;
    padding: 12px 20px;
    margin-top: 20px;
    text-align: center;
    font-size: 0.75rem;
    color: #666;
    box-shadow: 0 2px 10px rgba(0,0,0,0.03);
    width: 100%;
}

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

@media (max-width: 992px) {
    .sidebar {
        margin-left: -280px;
    }
    .main-content {
        margin-left: 0;
        width: 100%;
        padding: 12px 15px;
    }
}

@media (max-width: 768px) {
    .main-content {
        padding: 10px 12px;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 12px;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .summary-cards {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .filter-row {
        flex-direction: column;
        gap: 10px;
    }
    .filter-actions {
        flex-direction: row;
        flex-wrap: wrap;
    }
    .top-header {
        padding: 10px 15px;
        margin-bottom: 15px;
    }
    .footer {
        padding: 10px 15px;
        margin-top: 15px;
    }
    .table-card-header {
        flex-direction: column;
        align-items: stretch;
    }
    .cashflow-table th,
    .modern-table th {
        display: none;
    }
    .cashflow-table td,
    .modern-table td {
        display: block;
        text-align: right;
        padding-left: 50%;
        position: relative;
        border-bottom: none;
    }
    .cashflow-table td::before,
    .modern-table td::before {
        content: attr(data-label);
        position: absolute;
        left: 12px;
        width: 45%;
        text-align: left;
        font-weight: 700;
        font-size: 10px;
        color: #555;
    }
    .cashflow-table tr,
    .modern-table tr {
        display: block;
        margin-bottom: 10px;
        border: 1px solid #e8e8e8;
        border-radius: 12px;
        overflow: hidden;
    }
    .cashflow-table td:last-child,
    .modern-table td:last-child {
        border-bottom: none;
    }
    .summary-card {
        padding: 12px;
    }
    .summary-icon {
        width: 42px;
        height: 42px;
    }
    .summary-icon i {
        font-size: 20px;
    }
    .summary-content h4 {
        font-size: 18px;
    }
}

/* 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>
</head>
<body>
<div class="cashbook-closing-container">
    <!-- Page Header (outside PDF capture) -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-book"></i> Cash Book Closing Report</h2>
            <p>Complete cash flow statement with opening and closing balance</p>
        </div>
        <div class="header-right">
            <!--<button onclick="downloadPDF()" class="btn-pdf-header">-->
            <!--    <i class="fas fa-file-pdf"></i> Download PDF-->
            <!--</button>-->
            <div class="stats-badge">
                <i class="fas fa-chart-line"></i>
                <span>Cash Flow Report</span>
            </div>
        </div>
    </div>

    <!-- Filter Card (outside PDF capture) -->
    <div class="filter-card">
        <div class="filter-header">
            <i class="fas fa-filter"></i> Filter Report
        </div>
        <div class="filter-body">
            <form method="GET" action="" class="filter-form">
                <div class="filter-row">
                    <div class="filter-group">
                        <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="filter-group">
                        <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="filter-actions">
                        <button type="submit" class="btn-search">
                            <i class="fas fa-search"></i> Filter
                        </button>
                        <a href="cashbook_closing_report.php" class="btn-reset">
                            <i class="fas fa-sync-alt"></i> Reset
                        </a>
                        <button type="button" onclick="downloadPDF()" class="btn-pdf">
                            <i class="fas fa-file-pdf"></i> Download PDF
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Report Content (captured for PDF) -->
    <div id="report-content-cashbook">
        <!-- Summary Cards -->
        <div class="summary-cards">
            <div class="summary-card">
                <div class="summary-icon opening-icon">
                    <i class="fas fa-play-circle"></i>
                </div>
                <div class="summary-content">
                    <h4>Rs <?php echo number_format($opening_balance, 2); ?></h4>
                    <p>Opening Balance</p>
                    <small>As on <?php echo date('d-m-Y', strtotime($from_date)); ?></small>
                </div>
            </div>
            <div class="summary-card">
                <div class="summary-icon inflow-icon">
                    <i class="fas fa-arrow-down"></i>
                </div>
                <div class="summary-content">
                    <h4 class="text-success">Rs <?php echo number_format($total_inflows, 2); ?></h4>
                    <p>Total Inflows</p>
                    <small>Cash Received</small>
                </div>
            </div>
            <div class="summary-card">
                <div class="summary-icon outflow-icon">
                    <i class="fas fa-arrow-up"></i>
                </div>
                <div class="summary-content">
                    <h4 class="text-danger">Rs <?php echo number_format($total_outflows, 2); ?></h4>
                    <p>Total Outflows</p>
                    <small>Cash Paid</small>
                </div>
            </div>
            <div class="summary-card">
                <div class="summary-icon closing-icon">
                    <i class="fas fa-flag-checkered"></i>
                </div>
                <div class="summary-content">
                    <h4 class="<?php echo $closing_balance >= 0 ? 'text-success' : 'text-danger'; ?>">
                        Rs <?php echo number_format(abs($closing_balance), 2); ?>
                        <?php echo $closing_balance >= 0 ? 'Cr' : 'Dr'; ?>
                    </h4>
                    <p>Closing Balance</p>
                    <small>As on <?php echo date('d-m-Y', strtotime($to_date)); ?></small>
                </div>
            </div>
        </div>

        <!-- Cash Flow Breakdown Table -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-chart-line"></i>
                    <h4>Cash Flow Statement</h4>
                </div>
                <div class="table-stats">
                    Period: <?php echo date('d-m-Y', strtotime($from_date)); ?> to <?php echo date('d-m-Y', strtotime($to_date)); ?>
                </div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="cashflow-table">
                        <thead>
                            <tr>
                                <th width="50%">Description</th>
                                <th width="25%">Amount (Rs)</th>
                                <th width="25%">Details</th>
                            </tr>
                        </thead>
                        <tbody>
                            <!-- Opening Balance -->
                            <tr class="opening-row">
                                <td><strong><i class="fas fa-play-circle"></i> Opening Balance</strong></td>
                                <td class="text-right"><strong>Rs <?php echo number_format($opening_balance, 2); ?></strong></td>
                                <td class="text-muted">Balance brought forward</td>
                            </tr>
                            
                            <!-- CASH INFLOWS SECTION -->
                            <tr class="section-header">
                                <td colspan="3"><strong><i class="fas fa-arrow-down text-success"></i> CASH INFLOWS</strong></td>
                            </tr>
                            
                            <tr class="inflow-row">
                                <td><i class="fas fa-gas-pump"></i> Cash Sales (Fuel)</td>
                                <td class="text-right text-success">+ Rs <?php echo number_format($net_cash_sales, 2); ?></td>
                                <td class="text-muted">From nozzle readings (excl. credit)</td>
                            </tr>
                            
                            <tr class="inflow-row">
                                <td><i class="fas fa-hand-holding-usd"></i> Customer Payments</td>
                                <td class="text-right text-success">+ Rs <?php echo number_format($customer_recovery, 2); ?></td>
                                <td class="text-muted">Payments received from customers</td>
                            </tr>
                            
                            <tr class="inflow-row">
                                <td><i class="fas fa-money-bill-wave"></i> Customer Advance Deposits</td>
                                <td class="text-right text-success">+ Rs <?php echo number_format($customer_advance, 2); ?></td>
                                <td class="text-muted">Advance payments from customers</td>
                            </tr>
                            
                            <tr class="inflow-row">
                                <td><i class="fas fa-hand-holding-usd"></i> GP Payments Received</td>
                                <td class="text-right text-success">+ Rs <?php echo number_format($gp_received, 2); ?></td>
                                <td class="text-muted">From General Parties</td>
                            </tr>
                            
                            <tr class="total-row">
                                <td><strong>Total Cash Inflows</strong></td>
                                <td class="text-right"><strong>Rs <?php echo number_format($total_inflows, 2); ?></strong></td>
                                <td></td>
                            </tr>
                            
                            <!-- CASH OUTFLOWS SECTION -->
                            <tr class="section-header">
                                <td colspan="3"><strong><i class="fas fa-arrow-up text-danger"></i> CASH OUTFLOWS</strong></td>
                            </tr>
                            
                            <tr class="outflow-row">
                                <td><i class="fas fa-file-invoice-dollar"></i> Operating Expenses</td>
                                <td class="text-right text-danger">- Rs <?php echo number_format($expenses, 2); ?></td>
                                <td class="text-muted">General business expenses</td>
                            </tr>
                            
                            <tr class="outflow-row">
                                <td><i class="fas fa-truck"></i> Supplier Payments</td>
                                <td class="text-right text-danger">- Rs <?php echo number_format($supplier_payments, 2); ?></td>
                                <td class="text-muted">Payments to suppliers</td>
                            </tr>
                            
                            <tr class="outflow-row">
                                <td><i class="fas fa-hand-holding-usd"></i> GP Payments Given</td>
                                <td class="text-right text-danger">- Rs <?php echo number_format($gp_paid, 2); ?></td>
                                <td class="text-muted">Payments to General Parties</td>
                            </tr>
                            
                            <tr class="total-row">
                                <td><strong>Total Cash Outflows</strong></td>
                                <td class="text-right"><strong>Rs <?php echo number_format($total_outflows, 2); ?></strong></td>
                                <td></td>
                            </tr>
                            
                            <!-- NET CASH FLOW -->
                            <tr class="net-row">
                                <td><strong><i class="fas fa-calculator"></i> Net Cash Flow</strong></td>
                                <td class="text-right <?php echo ($total_inflows - $total_outflows) >= 0 ? 'text-success' : 'text-danger'; ?>">
                                    <strong><?php echo ($total_inflows - $total_outflows) >= 0 ? '+' : ''; ?> Rs <?php echo number_format(abs($total_inflows - $total_outflows), 2); ?></strong>
                                </td>
                                <td class="text-muted">Inflows - Outflows</td>
                            </tr>
                            
                            <!-- Closing Balance -->
                            <tr class="closing-row">
                                <td><strong><i class="fas fa-flag-checkered"></i> Closing Balance</strong></td>
                                <td class="text-right">
                                    <strong class="<?php echo $closing_balance >= 0 ? 'text-success' : 'text-danger'; ?>">
                                        Rs <?php echo number_format(abs($closing_balance), 2); ?>
                                        <?php echo $closing_balance >= 0 ? 'Cr' : 'Dr'; ?>
                                    </strong>
                                </td>
                                <td class="text-muted">Opening + Net Cash Flow</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        <!-- Recent Transactions -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-history"></i>
                    <h4>Recent Transactions</h4>
                </div>
                <div class="table-stats">
                    Last <?php echo count($transactions); ?> transactions
                </div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table">
                        <thead>
                            <tr>
                                <th>Date & Time</th>
                                <th>Transaction Type</th>
                                <th>Description</th>
                                <th>Amount (Rs)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(count($transactions) > 0): ?>
                                <?php foreach($transactions as $trans): ?>
                                    <tr>
                                        <td><?php echo date('d-m-Y H:i', strtotime($trans['date_time'])); ?></td>
                                        <td>
                                            <span class="trans-badge <?php echo (strpos($trans['type'], 'Cash Sale') !== false || strpos($trans['type'], 'Payment') !== false || strpos($trans['type'], 'Advance') !== false) ? 'inflow' : 'outflow'; ?>">
                                                <?php echo $trans['type']; ?>
                                            </span>
                                        </td>
                                        <td><?php echo htmlspecialchars(substr($trans['description'], 0, 60)); ?></td>
                                        <td class="<?php echo (strpos($trans['type'], 'Cash Sale') !== false || strpos($trans['type'], 'Payment') !== false || strpos($trans['type'], 'Advance') !== false) ? 'text-success' : 'text-danger'; ?>">
                                            <?php echo (strpos($trans['type'], 'Cash Sale') !== false || strpos($trans['type'], 'Payment') !== false || strpos($trans['type'], 'Advance') !== false) ? '+' : '-'; ?> 
                                            Rs <?php echo number_format($trans['amount'], 2); ?>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="empty-state">No transactions found for this period</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div><!-- end #report-content-cashbook -->
</div>

<script>
// Pass filter info to JS for PDF header
const pdfDateFrom = '<?php echo date('d-m-Y', strtotime($from_date)); ?>';
const pdfDateTo   = '<?php echo date('d-m-Y', strtotime($to_date)); ?>';
const reportTitle = 'Cash Book Closing Report';

async function downloadPDF() {
    const element = document.getElementById('report-content-cashbook');
    if (!element) {
        alert('No report content to download.');
        return;
    }

    // Disable all PDF buttons
    const pdfBtns = document.querySelectorAll('.btn-pdf-header, .btn-pdf');
    const originalHTMLs = Array.from(pdfBtns).map(btn => btn.innerHTML);
    pdfBtns.forEach(btn => {
        btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';
        btn.disabled = true;
    });

    try {
        // Capture the full content as one high-res canvas
        const canvas = await html2canvas(element, {
            scale: 2,
            useCORS: true,
            logging: false,
            allowTaint: true,
            backgroundColor: '#ffffff'
        });

        const { jsPDF } = window.jspdf;
        const pdf = new jsPDF('p', 'mm', 'a4');

        const pageWidthMM  = 210;
        const pageHeightMM = 297;
        const marginMM     = 10;
        const contentWidthMM = pageWidthMM - marginMM * 2;

        const headerHeightMM = 62;
        const bottomMarginMM = 10;
        const availHeightMM = pageHeightMM - headerHeightMM - bottomMarginMM;

        const pxPerMM = canvas.width / contentWidthMM;
        const totalImgHeightMM = canvas.height / pxPerMM;

        // ── Header drawing function ──────────────────────
        function addHeader() {
            pdf.setFont('helvetica', 'bold');
            pdf.setFontSize(18);
            pdf.setTextColor(160, 70, 87);
            pdf.text('ALFATEH PETROLEUM SERVICE', pageWidthMM / 2, 20, { align: 'center' });

            pdf.setFont('helvetica', 'normal');
            pdf.setFontSize(11);
            pdf.setTextColor(100, 100, 100);
            pdf.text('Complete Fuel Station Management Solution', pageWidthMM / 2, 27, { align: 'center' });

            pdf.setFontSize(10);
            pdf.setTextColor(80, 80, 80);
            pdf.text('Shaikh bhirkyo road Tando Muhammad khan', pageWidthMM / 2, 34, { align: 'center' });

            pdf.setDrawColor(160, 70, 87);
            pdf.setLineWidth(0.5);
            pdf.line(marginMM, 40, pageWidthMM - marginMM, 40);

            pdf.setFont('helvetica', 'bold');
            pdf.setFontSize(16);
            pdf.setTextColor(0, 0, 0);
            pdf.text(reportTitle, pageWidthMM / 2, 48, { align: 'center' });

            const periodText = `Period: ${pdfDateFrom} To ${pdfDateTo}`;
            pdf.setFont('helvetica', 'normal');
            pdf.setFontSize(10);
            pdf.setTextColor(80, 80, 80);
            pdf.text(periodText, pageWidthMM / 2, 55, { align: 'center' });

            pdf.setDrawColor(160, 70, 87);
            pdf.line(marginMM, 59, pageWidthMM - marginMM, 59);
        }

        // ── Slice-and-draw loop ──────────────────────────
        let remainingMM   = totalImgHeightMM;
        let sourceYpx     = 0;

        addHeader(); // header for page 1

        while (remainingMM > 0.5) {
            const sliceHeightMM = Math.min(remainingMM, availHeightMM);
            const sliceHeightPx = Math.round(sliceHeightMM * pxPerMM);

            const tmpCanvas = document.createElement('canvas');
            tmpCanvas.width  = canvas.width;
            tmpCanvas.height = sliceHeightPx;
            const ctx = tmpCanvas.getContext('2d');
            ctx.drawImage(
                canvas,
                0, sourceYpx,
                canvas.width, sliceHeightPx,
                0, 0,
                canvas.width, sliceHeightPx
            );

            const sliceDataURL = tmpCanvas.toDataURL('image/png');

            pdf.addImage(
                sliceDataURL, 'PNG',
                marginMM, headerHeightMM,
                contentWidthMM, sliceHeightMM
            );

            sourceYpx    += sliceHeightPx;
            remainingMM  -= sliceHeightMM;

            if (remainingMM > 0.5) {
                pdf.addPage();
                addHeader();
            }
        }

        const fileName = `Cash_Book_Closing_Report_${pdfDateFrom}_to_${pdfDateTo}.pdf`.replace(/\s+/g, '_');
        pdf.save(fileName);

    } catch (error) {
        console.error('Error generating PDF:', error);
        alert('An error occurred while generating the PDF. Please try again.');
    } finally {
        pdfBtns.forEach((btn, i) => {
            btn.innerHTML = originalHTMLs[i];
            btn.disabled = false;
        });
    }
}
</script>

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