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

// ============================================
// INCOME SECTION
// ============================================

// 1. FUEL SALES (Total sales from nozzle readings)
$fuel_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) BETWEEN '$from_date' AND '$to_date'";
$fuel_sales_result = mysqli_query($conn, $fuel_sales_sql);
$fuel_sales_data = mysqli_fetch_assoc($fuel_sales_result);
$fuel_sales = floatval($fuel_sales_data['total'] ?? 0);

// 2. LUBE SALES (Walk-in sales only)
$lube_sales_sql = "SELECT COALESCE(SUM(total_amount), 0) as total
                   FROM lube_sales 
                   WHERE customer_type = 'walkin'
                   AND DATE(sale_date) BETWEEN '$from_date' AND '$to_date'";
$lube_sales_result = mysqli_query($conn, $lube_sales_sql);
$lube_sales_data = mysqli_fetch_assoc($lube_sales_result);
$lube_sales = floatval($lube_sales_data['total'] ?? 0);

// 3. CUSTOMER PAYMENTS RECEIVED (Recovery)
$customer_recovery_sql = "SELECT COALESCE(SUM(amount), 0) as total
                          FROM customer_payments 
                          WHERE payment_type = 'payment'
                          AND DATE(date_time) BETWEEN '$from_date' AND '$to_date'";
$customer_recovery_result = mysqli_query($conn, $customer_recovery_sql);
$customer_recovery_data = mysqli_fetch_assoc($customer_recovery_result);
$customer_recovery = floatval($customer_recovery_data['total'] ?? 0);

// 4. CUSTOMER ADVANCE DEPOSITS
$customer_advance_sql = "SELECT COALESCE(SUM(amount), 0) as total
                         FROM customer_payments 
                         WHERE payment_type = 'advance'
                         AND DATE(date_time) BETWEEN '$from_date' AND '$to_date'";
$customer_advance_result = mysqli_query($conn, $customer_advance_sql);
$customer_advance_data = mysqli_fetch_assoc($customer_advance_result);
$customer_advance = floatval($customer_advance_data['total'] ?? 0);

// 5. GP RECEIVED (Party paid us)
$gp_received_sql = "SELECT COALESCE(SUM(amount), 0) as total
                    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 = floatval($gp_received_data['total'] ?? 0);

// Total Income
$total_income = $fuel_sales + $lube_sales + $customer_recovery + $customer_advance + $gp_received;

// ============================================
// COST OF GOODS SOLD (COGS)
// ============================================

// 1. FUEL PURCHASES (Cost of fuel purchased)
$fuel_purchases_sql = "SELECT COALESCE(SUM(total_amount), 0) as total
                       FROM purchases 
                       WHERE DATE(date_time) BETWEEN '$from_date' AND '$to_date'";
$fuel_purchases_result = mysqli_query($conn, $fuel_purchases_sql);
$fuel_purchases_data = mysqli_fetch_assoc($fuel_purchases_result);
$fuel_purchases = floatval($fuel_purchases_data['total'] ?? 0);

// 2. LUBE PURCHASES (Cost of lube purchased)
$lube_purchases_sql = "SELECT COALESCE(SUM(total_amount), 0) as total
                       FROM lube_purchases 
                       WHERE DATE(purchase_date) BETWEEN '$from_date' AND '$to_date'";
$lube_purchases_result = mysqli_query($conn, $lube_purchases_sql);
$lube_purchases_data = mysqli_fetch_assoc($lube_purchases_result);
$lube_purchases = floatval($lube_purchases_data['total'] ?? 0);

// Total COGS
$total_cogs = $fuel_purchases + $lube_purchases;

// ============================================
// GROSS PROFIT
// ============================================
$gross_profit = $total_income - $total_cogs;
$gross_margin_percent = $total_income > 0 ? ($gross_profit / $total_income) * 100 : 0;

// ============================================
// OPERATING EXPENSES
// ============================================

// 1. GENERAL EXPENSES
$expenses_sql = "SELECT COALESCE(SUM(COALESCE(amount, expense_amount)), 0) as total
                 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);
$general_expenses = floatval($expenses_data['total'] ?? 0);

// Get expense breakdown by category
$expense_breakdown_sql = "SELECT 
                            CASE 
                                WHEN category = '' OR category IS NULL THEN 'Other'
                                ELSE category 
                            END as category_name,
                            COALESCE(SUM(COALESCE(amount, expense_amount)), 0) as total
                          FROM expenses 
                          WHERE DATE(date_time) BETWEEN '$from_date' AND '$to_date'
                          GROUP BY category_name
                          ORDER BY total DESC";
$expense_breakdown_result = mysqli_query($conn, $expense_breakdown_sql);

// 2. SUPPLIER PAYMENTS (Operating expense)
$supplier_payments_sql = "SELECT COALESCE(SUM(amount), 0) as total
                          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 = floatval($supplier_payments_data['total'] ?? 0);

// 3. GP PAID (Payments to General Parties)
$gp_paid_sql = "SELECT COALESCE(SUM(amount), 0) as total
                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 = floatval($gp_paid_data['total'] ?? 0);

// Total Operating Expenses
$total_operating_expenses = $general_expenses + $supplier_payments + $gp_paid;

// ============================================
// NET PROFIT
// ============================================
$net_profit = $gross_profit - $total_operating_expenses;
$net_margin_percent = $total_income > 0 ? ($net_profit / $total_income) * 100 : 0;

// ============================================
// GET DETAILED TRANSACTIONS FOR DISPLAY
// ============================================

// Get recent sales for display
$recent_sales_sql = "(SELECT 'Fuel Sale' as type, date_time, 
                             (sale_liters * ft.sale_price) as amount,
                             CONCAT(ft.name, ' - ', 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'
                      LIMIT 5)
                      UNION ALL
                      (SELECT 'Lube Sale' as type, sale_date as date_time, total_amount as amount,
                              CONCAT('Invoice: ', sale_invoice) as description
                       FROM lube_sales 
                       WHERE customer_type = 'walkin'
                       AND DATE(sale_date) BETWEEN '$from_date' AND '$to_date'
                       LIMIT 5)
                      ORDER BY date_time DESC
                      LIMIT 15";
$recent_sales_result = mysqli_query($conn, $recent_sales_sql);
?>

<?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>Profit & Loss Statement</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>
        /* Profit & Loss 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,
.section-header h3,
.recent-header 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;
}

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

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

.stats-badge {
    background: rgba(255,255,255,0.2);
    padding: 6px 16px;
    border-radius: 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;
}

/* 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-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-pdf {
    background: #dc3545;
    color: #fff;
}

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

/* Period Info - COMPACT */
.period-info {
    background: #e3f2fd;
    padding: 10px 16px;
    border-radius: 10px;
    margin-bottom: 20px;
    font-size: 12px;
    color: #1565c0;
    display: inline-block;
}

/* PL Main Card - COMPACT */
.pl-main-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%;
}

.pl-section {
    border-bottom: 1px solid #f0f0f0;
}

.pl-section:last-child {
    border-bottom: none;
}

.section-header {
    padding: 12px 20px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.section-header i {
    font-size: 18px;
}

.section-header h3 {
    margin: 0;
    font-size: 15px;
    font-weight: 700;
}

.income-header {
    background: #e8f5e9;
    color: #2e7d32;
}

.cogs-header {
    background: #fff3e0;
    color: #e65100;
}

.gross-profit-header {
    background: #e3f2fd;
    color: #1565c0;
}

.expense-header {
    background: #ffebee;
    color: #c62828;
}

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

.section-body {
    padding: 12px 20px;
}

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

.pl-row:last-child {
    border-bottom: none;
}

.pl-label {
    font-size: 13px;
    color: #444;
    display: flex;
    align-items: center;
    gap: 6px;
}

.pl-label i {
    color: #A04657;
    width: 18px;
    font-size: 14px;
}

.pl-amount {
    font-size: 13px;
    font-weight: 500;
}

.total-row {
    background: #f8f9fc;
    margin-top: 5px;
    padding: 10px 0;
    border-radius: 8px;
}

.total-row .pl-label,
.total-row .pl-amount {
    font-weight: 700;
    font-size: 14px;
}

.income-total {
    color: #28a745;
}

.cogs-total {
    color: #ff9800;
}

.expense-total {
    color: #dc3545;
}

.gross-profit-amount {
    color: #1565c0;
    font-size: 16px;
}

.margin-badge {
    font-size: 10px;
    font-weight: normal;
    color: #666;
    margin-left: 6px;
}

.net-profit {
    color: #28a745;
    font-size: 22px;
    font-weight: 800;
}

.net-loss {
    color: #dc3545;
    font-size: 22px;
    font-weight: 800;
}

/* Expense Breakdown - COMPACT */
.expense-breakdown {
    background: #fafafa;
    padding: 10px 12px;
    border-radius: 10px;
    margin: 8px 0;
}

.breakdown-title {
    font-size: 11px;
    font-weight: 600;
    color: #666;
    margin-bottom: 6px;
}

.breakdown-item {
    display: flex;
    justify-content: space-between;
    padding: 4px 0;
    font-size: 11px;
    border-bottom: 1px dotted #e0e0e0;
}

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

.breakdown-label {
    color: #555;
}

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

/* Net Summary */
.net-summary {
    display: flex;
    justify-content: space-between;
    margin-top: 12px;
    padding-top: 12px;
    border-top: 1px solid #e0e0e0;
}

.net-summary-item {
    font-size: 12px;
}

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

.text-danger {
    color: #dc3545;
}

/* Recent Card - COMPACT */
.recent-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%;
}

.recent-header {
    background: #f8f9fc;
    padding: 12px 20px;
    border-bottom: 1px solid #e8e8e8;
    display: flex;
    align-items: center;
    gap: 8px;
}

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

.recent-header h4 {
    margin: 0;
    font-size: 15px;
    font-weight: 600;
}

.recent-body {
    padding: 0;
}

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

.recent-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 12px;
    min-width: 700px;
}

.recent-table th {
    padding: 10px 14px;
    background: #fafbfc;
    font-weight: 700;
    color: #445566;
    font-size: 11px;
    text-transform: uppercase;
    border-bottom: 1px solid #e8e8e8;
}

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

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

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

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

.amount-positive {
    color: #28a745;
    font-weight: 600;
}

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

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

.empty-state p {
    font-size: 12px;
}

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

/* Print Styles */
@media print {
    .sidebar, .top-header, .footer, .filter-card, .stats-badge, .btn-pdf, .btn-search, .page-header .header-right, .btn-pdf-header {
        display: none !important;
    }
    .main-content {
        margin: 0;
        padding: 0;
        width: 100%;
    }
    .pl-main-card {
        box-shadow: none;
        border: 1px solid #ddd;
    }
    .page-header {
        background: #A04657;
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
    .section-header {
        -webkit-print-color-adjust: exact;
        print-color-adjust: exact;
    }
}

/* Responsive */
@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;
    }
    .pl-container {
        padding: 0;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 12px;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .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;
    }
    .pl-row {
        flex-direction: column;
        align-items: flex-start;
        gap: 4px;
    }
    .net-summary {
        flex-direction: column;
        gap: 8px;
    }
    .recent-table th,
    .recent-table td {
        padding: 8px 12px;
        font-size: 11px;
    }
    .section-body {
        padding: 10px 16px;
    }
    .section-header {
        padding: 10px 16px;
    }
}

/* 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="pl-container">
    <!-- Page Header (outside PDF capture) -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-chart-line"></i> Profit & Loss Statement</h2>
            <p>Complete financial performance report for the period</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-calendar"></i>
                <span><?php echo date('d-m-Y H:i'); ?></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> Generate Report
                        </button>
                        <button type="button" onclick="downloadPDF()" class="btn-pdf">
                            <i class="fas fa-file-pdf"></i> Download PDF
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- PDF Report Content -->
    <div id="report-content-pl">
        <!-- Period Info -->
        <div class="period-info">
            <i class="fas fa-calendar-week"></i>
            Report Period: <strong><?php echo date('d-m-Y', strtotime($from_date)); ?></strong> to <strong><?php echo date('d-m-Y', strtotime($to_date)); ?></strong>
        </div>

        <!-- Profit & Loss Main Card -->
        <div class="pl-main-card">
            <!-- INCOME SECTION -->
            <div class="pl-section">
                <div class="section-header income-header">
                    <i class="fas fa-arrow-down"></i>
                    <h3>INCOME (Revenue)</h3>
                </div>
                <div class="section-body">
                    <div class="pl-row">
                        <div class="pl-label">
                            <i class="fas fa-gas-pump"></i> Fuel Sales Revenue
                        </div>
                        <div class="pl-amount">Rs <?php echo number_format($fuel_sales, 2); ?></div>
                    </div>
                    <div class="pl-row">
                        <div class="pl-label">
                            <i class="fas fa-oil-can"></i> Lube Sales Revenue
                        </div>
                        <div class="pl-amount">Rs <?php echo number_format($lube_sales, 2); ?></div>
                    </div>
                    <div class="pl-row">
                        <div class="pl-label">
                            <i class="fas fa-hand-holding-usd"></i> Customer Recovery
                        </div>
                        <div class="pl-amount">Rs <?php echo number_format($customer_recovery, 2); ?></div>
                    </div>
                    <div class="pl-row">
                        <div class="pl-label">
                            <i class="fas fa-money-bill-wave"></i> Customer Advance Deposits
                        </div>
                        <div class="pl-amount">Rs <?php echo number_format($customer_advance, 2); ?></div>
                    </div>
                    <div class="pl-row">
                        <div class="pl-label">
                            <i class="fas fa-hand-holding-usd"></i> GP Payments Received
                        </div>
                        <div class="pl-amount">Rs <?php echo number_format($gp_received, 2); ?></div>
                    </div>
                    <div class="pl-row total-row">
                        <div class="pl-label"><strong>TOTAL INCOME</strong></div>
                        <div class="pl-amount income-total"><strong>Rs <?php echo number_format($total_income, 2); ?></strong></div>
                    </div>
                </div>
            </div>

            <!-- COST OF GOODS SOLD SECTION -->
            <div class="pl-section">
                <div class="section-header cogs-header">
                    <i class="fas fa-shopping-cart"></i>
                    <h3>COST OF GOODS SOLD (COGS)</h3>
                </div>
                <div class="section-body">
                    <div class="pl-row">
                        <div class="pl-label">
                            <i class="fas fa-truck"></i> Fuel Purchases
                        </div>
                        <div class="pl-amount cogs-amount">Rs <?php echo number_format($fuel_purchases, 2); ?></div>
                    </div>
                    <div class="pl-row">
                        <div class="pl-label">
                            <i class="fas fa-shopping-cart"></i> Lube Purchases
                        </div>
                        <div class="pl-amount cogs-amount">Rs <?php echo number_format($lube_purchases, 2); ?></div>
                    </div>
                    <div class="pl-row total-row">
                        <div class="pl-label"><strong>TOTAL COGS</strong></div>
                        <div class="pl-amount cogs-total"><strong>Rs <?php echo number_format($total_cogs, 2); ?></strong></div>
                    </div>
                </div>
            </div>

            <!-- GROSS PROFIT SECTION -->
            <div class="pl-section highlight">
                <div class="section-header gross-profit-header">
                    <i class="fas fa-chart-line"></i>
                    <h3>GROSS PROFIT</h3>
                </div>
                <div class="section-body">
                    <div class="pl-row">
                        <div class="pl-label">
                            <i class="fas fa-calculator"></i> Gross Profit = Total Income - COGS
                        </div>
                        <div class="pl-amount gross-profit-amount">
                            <strong>Rs <?php echo number_format($gross_profit, 2); ?></strong>
                            <span class="margin-badge">(<?php echo number_format($gross_margin_percent, 2); ?>% margin)</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- OPERATING EXPENSES SECTION -->
            <div class="pl-section">
                <div class="section-header expense-header">
                    <i class="fas fa-arrow-up"></i>
                    <h3>OPERATING EXPENSES</h3>
                </div>
                <div class="section-body">
                    <div class="pl-row">
                        <div class="pl-label">
                            <i class="fas fa-file-invoice-dollar"></i> General Expenses
                        </div>
                        <div class="pl-amount expense-amount">Rs <?php echo number_format($general_expenses, 2); ?></div>
                    </div>
                    
                    <!-- Expense Breakdown -->
                    <?php if($expense_breakdown_result && mysqli_num_rows($expense_breakdown_result) > 0): ?>
                        <div class="expense-breakdown">
                            <div class="breakdown-title">Expense Breakdown:</div>
                            <?php while($exp = mysqli_fetch_assoc($expense_breakdown_result)): ?>
                                <div class="breakdown-item">
                                    <span class="breakdown-label">- <?php echo htmlspecialchars($exp['category_name']); ?>:</span>
                                    <span class="breakdown-amount">Rs <?php echo number_format($exp['total'], 2); ?></span>
                                </div>
                            <?php endwhile; ?>
                        </div>
                    <?php endif; ?>
                    
                    <div class="pl-row">
                        <div class="pl-label">
                            <i class="fas fa-truck"></i> Supplier Payments
                        </div>
                        <div class="pl-amount expense-amount">Rs <?php echo number_format($supplier_payments, 2); ?></div>
                    </div>
                    <div class="pl-row">
                        <div class="pl-label">
                            <i class="fas fa-hand-holding-usd"></i> GP Payments Given
                        </div>
                        <div class="pl-amount expense-amount">Rs <?php echo number_format($gp_paid, 2); ?></div>
                    </div>
                    <div class="pl-row total-row">
                        <div class="pl-label"><strong>TOTAL OPERATING EXPENSES</strong></div>
                        <div class="pl-amount expense-total"><strong>Rs <?php echo number_format($total_operating_expenses, 2); ?></strong></div>
                    </div>
                </div>
            </div>

            <!-- NET PROFIT SECTION -->
            <div class="pl-section net-section">
                <div class="section-header net-header">
                    <i class="fas fa-chart-pie"></i>
                    <h3>NET PROFIT / (LOSS)</h3>
                </div>
                <div class="section-body">
                    <div class="pl-row">
                        <div class="pl-label">
                            <i class="fas fa-calculator"></i> Net Profit = Gross Profit - Operating Expenses
                        </div>
                        <div class="pl-amount <?php echo $net_profit >= 0 ? 'net-profit' : 'net-loss'; ?>">
                            <strong>Rs <?php echo number_format(abs($net_profit), 2); ?></strong>
                            <span class="margin-badge">(<?php echo $net_profit >= 0 ? 'Profit' : 'Loss'; ?>)</span>
                        </div>
                    </div>
                    <div class="net-summary">
                        <div class="net-summary-item">
                            <span>Net Margin:</span>
                            <strong class="<?php echo $net_margin_percent >= 0 ? 'text-success' : 'text-danger'; ?>">
                                <?php echo number_format($net_margin_percent, 2); ?>%
                            </strong>
                        </div>
                        <div class="net-summary-item">
                            <span>Period:</span>
                            <strong><?php echo date('d-m-Y', strtotime($from_date)); ?> to <?php echo date('d-m-Y', strtotime($to_date)); ?></strong>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Recent Transactions -->
        <div class="recent-card">
            <div class="recent-header">
                <i class="fas fa-history"></i>
                <h4>Recent Income Transactions</h4>
            </div>
            <div class="recent-body">
                <div class="table-responsive">
                    <table class="recent-table">
                        <thead>
                            <tr>
                                <th>Date</th>
                                <th>Type</th>
                                <th>Description</th>
                                <th>Amount (Rs)</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if($recent_sales_result && mysqli_num_rows($recent_sales_result) > 0): ?>
                                <?php while($sale = mysqli_fetch_assoc($recent_sales_result)): ?>
                                    <tr>
                                        <td><?php echo date('d-m-Y H:i', strtotime($sale['date_time'])); ?></td>
                                        <td>
                                            <span class="type-badge <?php echo strpos($sale['type'], 'Fuel') !== false ? 'fuel-badge' : 'lube-badge'; ?>">
                                                <?php echo $sale['type']; ?>
                                            </span>
                                        </td>
                                        <td><?php echo htmlspecialchars($sale['description']); ?></td>
                                        <td class="amount-positive">+ Rs <?php echo number_format($sale['amount'], 2); ?></td>
                                    </tr>
                                <?php endwhile; ?>
                            <?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-pl -->
</div>

<!-- PDF Generation Script -->
<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 = 'Profit & Loss Statement';

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

    // Disable both PDF buttons (header and filter)
    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 = `Profit_Loss_Statement_${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>