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

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

// Get filter values
$shift_filter = isset($_GET['shift_filter']) ? mysqli_real_escape_string($conn, $_GET['shift_filter']) : '';
$start_date = isset($_GET['start_date']) ? $_GET['start_date'] : '';
$end_date = isset($_GET['end_date']) ? $_GET['end_date'] : '';

// Build WHERE clause for filters
$where_conditions = ["s.status = 'CLOSED'"];

if(!empty($shift_filter)) {
    $where_conditions[] = "s.shift_name = '$shift_filter'";
}

if(!empty($start_date) && !empty($end_date)) {
    $where_conditions[] = "DATE(s.date_time) BETWEEN '$start_date' AND '$end_date'";
} elseif(!empty($start_date)) {
    $where_conditions[] = "DATE(s.date_time) >= '$start_date'";
} elseif(!empty($end_date)) {
    $where_conditions[] = "DATE(s.date_time) <= '$end_date'";
}

$where_clause = implode(" AND ", $where_conditions);

// Get shift-wise sales report
$sql = "SELECT 
            s.id as shift_id,
            s.shift_name,
            s.date_time as shift_opened,
            COUNT(DISTINCT nr.id) as reading_count,
            SUM(nr.sale_liters) as total_liters,
            SUM(nr.sale_liters * f.sale_price) as total_amount
        FROM shift_entries s
        LEFT JOIN nozzle_readings nr ON s.id = nr.shift_id
        LEFT JOIN nozzles n ON nr.nozzle_id = n.id
        LEFT JOIN tanks t ON n.tank_id = t.id
        LEFT JOIN fuel_types f ON t.fuel_type_id = f.id
        WHERE $where_clause
        GROUP BY s.id
        ORDER BY s.id DESC";
$result = mysqli_query($conn, $sql);

// Get overall totals
$total_all_liters = 0;
$total_all_amount = 0;
$total_readings = 0;
$total_shifts = mysqli_num_rows($result);

// Get today's shifts count
$today_date = date('Y-m-d');
$today_shifts_sql = "SELECT COUNT(*) as today_count FROM shift_entries 
                     WHERE status='CLOSED' AND DATE(date_time) = '$today_date'";
$today_shifts_result = mysqli_query($conn, $today_shifts_sql);
$today_shifts_data = mysqli_fetch_assoc($today_shifts_result);
$today_shifts = $today_shifts_data['today_count'];

while($row = mysqli_fetch_assoc($result)) {
    $total_all_liters += $row['total_liters'];
    $total_all_amount += $row['total_amount'];
    $total_readings += $row['reading_count'];
}
mysqli_data_seek($result, 0);
?>

<?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>Sales Report (Shift-wise)</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>
       /* Sales Report Styles - FULL WIDTH, NO EXTRA SPACING */
/* Google Fonts - Poppins */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');

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

body {
    background: #f5f7fb;
    font-size: 14px;
    overflow-x: hidden;
}

/* Headings - Poppins */
h1, h2, h3, h4, h5, h6,
.page-header h2,
.stat-info h3,
.filter-header h4,
.header-info h4,
.modern-table th {
    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;
}

.sales-report-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;
    flex-wrap: wrap;
    gap: 12px;
    color: #fff;
    box-shadow: 0 4px 15px rgba(160,70,87,0.2);
    width: 100%;
}

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

.page-header h2 i {
    margin-right: 10px;
}

.page-header p {
    font-size: 12px;
    opacity: 0.92;
}

.header-right {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
}

.btn-back, .btn-pdf {
    background: rgba(255,255,255,0.2);
    color: #fff;
    padding: 6px 18px;
    border-radius: 40px;
    text-decoration: none;
    font-weight: 600;
    font-size: 12px;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.3s;
    border: none;
    cursor: pointer;
}

.btn-back:hover, .btn-pdf:hover {
    background: rgba(255,255,255,0.3);
    transform: translateX(-2px);
}

.btn-pdf {
    background: #dc3545;
}

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

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

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

.filter-header {
    background: #f8fafc;
    padding: 12px 20px;
    border-bottom: 1px solid #eef2f6;
    display: flex;
    align-items: center;
    gap: 10px;
}

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

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

.filter-body {
    padding: 16px 20px;
}

.filter-form {
    width: 100%;
}

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

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

.filter-group label {
    display: block;
    margin-bottom: 6px;
    font-weight: 600;
    font-size: 12px;
    color: #1e293b;
}

.filter-group label i {
    margin-right: 6px;
    color: #A04657;
}

.filter-select, .filter-date {
    width: 100%;
    padding: 8px 12px;
    border: 2px solid #e2e8f0;
    border-radius: 10px;
    font-size: 13px;
    font-weight: 500;
    background: #fefefe;
    transition: all 0.3s;
}

.filter-select:focus, .filter-date:focus {
    border-color: #A04657;
    outline: none;
    box-shadow: 0 0 0 3px rgba(160,70,87,0.08);
}

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

.btn-filter, .btn-reset {
    padding: 8px 20px;
    border-radius: 40px;
    font-weight: 600;
    font-size: 13px;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    transition: all 0.3s;
    border: none;
}

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

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

.btn-reset {
    background: #f1f5f9;
    color: #475569;
    text-decoration: none;
}

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

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

.stat-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);
    border: 1px solid #eef2f6;
    transition: all 0.3s;
    border-left: 4px solid #A04657;
}

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

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

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

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

.stat-info p {
    margin: 4px 0 0;
    font-weight: 500;
    color: #64748b;
    font-size: 11px;
}

.stat-trend {
    font-size: 10px;
    color: #94a3b8;
    display: block;
    margin-top: 3px;
}

/* Today Card - COMPACT */
.today-card {
    background: #fff;
    border-radius: 16px;
    margin-bottom: 20px;
    border: 1px solid #eef2f6;
    overflow: hidden;
    width: 100%;
}

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

.today-header i {
    font-size: 16px;
}

.today-header h5 {
    margin: 0;
    font-size: 14px;
    font-weight: 600;
}

.today-header span {
    margin-left: auto;
    font-size: 11px;
    opacity: 0.9;
}

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

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

.today-item span {
    font-size: 12px;
    color: #64748b;
    font-weight: 500;
}

.today-item span i {
    color: #A04657;
    margin-right: 5px;
}

.today-item strong {
    font-size: 14px;
    font-weight: 700;
    color: #1e293b;
}

.status-active {
    color: #28a745;
    font-weight: 700;
}

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

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

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

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

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

.table-search {
    position: relative;
}

.table-search i {
    position: absolute;
    left: 12px;
    top: 50%;
    transform: translateY(-50%);
    color: #94a3b8;
    font-size: 13px;
}

.search-input {
    padding: 8px 12px 8px 38px;
    border: 2px solid #e2e8f0;
    border-radius: 40px;
    width: 240px;
    font-size: 13px;
    font-weight: 500;
    transition: all 0.3s;
}

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

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

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

.modern-table th {
    padding: 10px 12px;
    background: #f8fafc;
    font-weight: 700;
    color: #475569;
    font-size: 12px;
    border-bottom: 2px solid #eef2f6;
    text-align: left;
}

.modern-table td {
    padding: 10px 12px;
    border-bottom: 1px solid #f0f4f9;
    font-size: 12px;
    font-weight: 500;
    color: #1e293b;
    vertical-align: middle;
}

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

.col-id {
    text-align: center;
    font-weight: 700;
    color: #A04657;
}

.shift-name-cell {
    display: flex;
    align-items: center;
    gap: 8px;
}

.shift-name-cell i {
    font-size: 14px;
}

.shift-name-cell strong {
    font-size: 13px;
    font-weight: 700;
}

.date-cell {
    display: flex;
    flex-direction: column;
    gap: 2px;
}

.date-main {
    font-size: 11px;
    font-weight: 600;
    color: #1e293b;
}

.time-main {
    font-size: 10px;
    color: #94a3b8;
}

.reading-cell, .liters-cell, .price-cell, .amount-cell {
    display: flex;
    align-items: center;
    gap: 6px;
}

.reading-cell i, .liters-cell i {
    color: #A04657;
    font-size: 12px;
}

.reading-cell strong, .liters-cell strong, .amount-cell strong {
    font-size: 13px;
    font-weight: 700;
}

.amount-cell strong {
    color: #28a745;
}

.price-cell {
    font-size: 12px;
    font-weight: 600;
}

/* Grand Total Row */
.grand-total {
    background: #f8fafc;
    border-top: 2px solid #eef2f6;
}

.grand-total td {
    font-weight: 800;
    font-size: 13px;
    color: #A04657;
    padding: 10px 12px;
}

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

/* Empty State */
.empty-state {
    text-align: center;
    padding: 40px 20px !important;
}

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

.empty-state p {
    font-size: 13px;
    font-weight: 600;
    color: #475569;
    margin-bottom: 6px;
}

.empty-state small {
    font-size: 11px;
    color: #94a3b8;
}

/* 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) {
    .stats-row {
        grid-template-columns: repeat(2, 1fr);
    }
    .filter-row {
        flex-direction: column;
        align-items: stretch;
    }
    .filter-actions {
        justify-content: stretch;
    }
    .btn-filter, .btn-reset {
        flex: 1;
        justify-content: center;
    }
}

@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;
    }
    .sales-report-container {
        padding: 0;
    }
    .page-header {
        flex-direction: column;
        text-align: center;
        gap: 10px;
        padding: 14px 18px;
    }
    .page-header h2 {
        font-size: 18px;
    }
    .header-right {
        justify-content: center;
    }
    .stats-row {
        grid-template-columns: 1fr;
        gap: 12px;
    }
    .today-body {
        flex-direction: column;
        text-align: center;
    }
    .table-card-header {
        flex-direction: column;
        align-items: stretch;
    }
    .search-input {
        width: 100%;
    }
    .top-header {
        padding: 10px 15px;
        margin-bottom: 15px;
    }
    .footer {
        padding: 10px 15px;
        margin-top: 15px;
    }
    .stat-card {
        padding: 12px;
    }
    .stat-icon {
        width: 44px;
        height: 44px;
    }
    .stat-icon i {
        font-size: 20px;
    }
    .stat-info h3 {
        font-size: 20px;
    }
    .modern-table {
        min-width: 650px;
    }
}

/* 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="sales-report-container">
    <!-- Page Header -->
    <div class="page-header">
        <div class="header-left">
            <h2><i class="fas fa-chart-bar"></i> Sales Report (Shift-wise)</h2>
            <p>Analyze shift performance and sales data across all closed shifts</p>
        </div>
        <div class="header-right">
            <a href="dashboard.php" class="btn-back"><i class="fas fa-arrow-left"></i> Back to Dashboard</a>
            <button onclick="downloadPDF()" class="btn-pdf"><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 Section (outside PDF capture) -->
    <div class="filter-card">
        <div class="filter-header">
            <i class="fas fa-filter"></i>
            <h4>Filter Reports</h4>
        </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-door-open"></i> Shift Name</label>
                        <select name="shift_filter" class="filter-select">
                            <option value="">-- All Shifts --</option>
                            <option value="Morning" <?php echo ($shift_filter == 'Morning') ? 'selected' : ''; ?>>🌅 Morning Shift</option>
                            <option value="Evening" <?php echo ($shift_filter == 'Evening') ? 'selected' : ''; ?>>🌤️ Evening Shift</option>
                            <option value="Night" <?php echo ($shift_filter == 'Night') ? 'selected' : ''; ?>>🌙 Night Shift</option>
                        </select>
                    </div>
                    <div class="filter-group">
                        <label><i class="fas fa-calendar-alt"></i> Start Date</label>
                        <input type="date" name="start_date" class="filter-date" value="<?php echo $start_date; ?>">
                    </div>
                    <div class="filter-group">
                        <label><i class="fas fa-calendar-alt"></i> End Date</label>
                        <input type="date" name="end_date" class="filter-date" value="<?php echo $end_date; ?>">
                    </div>
                    <div class="filter-actions">
                        <button type="submit" class="btn-filter"><i class="fas fa-search"></i> Apply Filter</button>
                        <?php if(!empty($shift_filter) || !empty($start_date) || !empty($end_date)): ?>
                            <a href="sales_report.php" class="btn-reset"><i class="fas fa-undo-alt"></i> Reset</a>
                        <?php endif; ?>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- PDF Report Content -->
    <div id="report-content-sales">
        <!-- Statistics Cards -->
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-door-closed"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo $total_shifts; ?></h3>
                    <p>Total Shifts</p>
                    <span class="stat-trend">Closed Shifts</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-tachometer-alt"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo number_format($total_all_liters, 2); ?> L</h3>
                    <p>Total Fuel Sold</p>
                    <span class="stat-trend">Across all shifts</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-rupee-sign"></i>
                </div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_all_amount, 2); ?></h3>
                    <p>Total Revenue</p>
                    <span class="stat-trend">Total Sales Value</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon">
                    <i class="fas fa-book"></i>
                </div>
                <div class="stat-info">
                    <h3><?php echo $total_readings; ?></h3>
                    <p>Total Readings</p>
                    <span class="stat-trend">Nozzle Records</span>
                </div>
            </div>
        </div>

        <!-- Today's Summary Card -->
        <div class="today-card">
            <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><i class="fas fa-door-closed"></i> Shifts Closed Today:</span>
                    <strong><?php echo $today_shifts; ?></strong>
                </div>
                <div class="today-item">
                    <span><i class="fas fa-chart-line"></i> Status:</span>
                    <strong class="status-active">Reporting Active</strong>
                </div>
            </div>
        </div>

        <!-- Sales Report Table -->
        <div class="table-card">
            <div class="table-card-header">
                <div class="header-info">
                    <i class="fas fa-chart-line"></i>
                    <h4>Shift-wise Sales Summary</h4>
                </div>
                <div class="table-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="tableSearch" placeholder="Search shift..." class="search-input">
                </div>
            </div>
            <div class="table-card-body">
                <div class="table-responsive">
                    <table class="modern-table" id="salesTable">
                        <thead>
                            <tr>
                                <th style="width: 60px; text-align: center;">#</th>
                                <th style="width: 180px;">Shift Name</th>
                                <th style="width: 160px;">Shift Opened</th>
                                <th style="width: 120px; text-align: center;">Readings</th>
                                <th style="width: 140px; text-align: right;">Total Liters</th>
                                <th style="width: 160px; text-align: right;">Total Amount</th>
                                <th style="width: 130px; text-align: right;">Avg Price/L</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $counter = 1;
                            if(mysqli_num_rows($result) > 0): 
                                while($row = mysqli_fetch_assoc($result)):
                                    $avg_price = ($row['total_liters'] > 0) ? $row['total_amount'] / $row['total_liters'] : 0;
                                    
                                    if($row['shift_name'] == 'Morning') {
                                        $shift_icon = 'fa-sun';
                                        $shift_color = '#f39c12';
                                    } elseif($row['shift_name'] == 'Evening') {
                                        $shift_icon = 'fa-cloud-sun';
                                        $shift_color = '#e67e22';
                                    } else {
                                        $shift_icon = 'fa-moon';
                                        $shift_color = '#8e44ad';
                                    }
                            ?>
                                <tr>
                                    <td class="col-id"><?php echo $counter++; ?></td>
                                    <td>
                                        <div class="shift-name-cell">
                                            <i class="fas <?php echo $shift_icon; ?>" style="color: <?php echo $shift_color; ?>"></i>
                                            <strong><?php echo $row['shift_name']; ?> Shift</strong>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="date-cell">
                                            <span class="date-main"><?php echo date('d-m-Y', strtotime($row['shift_opened'])); ?></span>
                                            <span class="time-main"><?php echo date('h:i A', strtotime($row['shift_opened'])); ?></span>
                                        </div>
                                    </td>
                                    <td style="text-align: center;">
                                        <div class="reading-cell">
                                            <i class="fas fa-book"></i>
                                            <strong><?php echo $row['reading_count']; ?></strong>
                                        </div>
                                    </td>
                                    <td style="text-align: right;">
                                        <div class="liters-cell">
                                            <i class="fas fa-tachometer-alt"></i>
                                            <strong><?php echo number_format($row['total_liters'], 2); ?> L</strong>
                                        </div>
                                    </td>
                                    <td style="text-align: right;">
                                        <div class="amount-cell">
                                            <strong>Rs <?php echo number_format($row['total_amount'], 2); ?></strong>
                                        </div>
                                    </td>
                                    <td style="text-align: right;">
                                        <div class="price-cell">
                                            Rs <?php echo number_format($avg_price, 2); ?>/L
                                        </div>
                                    </td>
                                </tr>
                            <?php 
                                endwhile;
                            else: 
                            ?>
                                <tr>
                                    <td colspan="7" class="empty-state">
                                        <i class="fas fa-chart-line"></i>
                                        <p>No closed shifts found</p>
                                        <small>Complete and close shifts to see sales reports</small>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                        <?php if(mysqli_num_rows($result) > 0): ?>
                            <tfoot>
                                <tr class="grand-total">
                                    <td colspan="3" style="text-align: right;"><strong>GRAND TOTAL:</strong></td>
                                    <td style="text-align: center;"><strong><?php echo $total_readings; ?></strong></td>
                                    <td style="text-align: right;"><strong><?php echo number_format($total_all_liters, 2); ?> L</strong></td>
                                    <td style="text-align: right;"><strong>Rs <?php echo number_format($total_all_amount, 2); ?></strong></td>
                                    <td style="text-align: right;"><strong>Rs <?php echo ($total_all_liters > 0) ? number_format($total_all_amount / $total_all_liters, 2) : '0.00'; ?>/L</strong></td>
                                </tr>
                            </tfoot>
                        <?php endif; ?>
                    </table>
                </div>
            </div>
        </div>
    </div><!-- end #report-content-sales -->
</div>

<script>
// Pass filter info to JS for PDF header
const pdfStartDate = '<?php echo $start_date ? date('d-m-Y', strtotime($start_date)) : "All Dates"; ?>';
const pdfEndDate   = '<?php echo $end_date   ? date('d-m-Y', strtotime($end_date))   : "All Dates"; ?>';
const reportTitle  = 'Sales Report (Shift-wise)';

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

    const pdfBtn = document.querySelector('.btn-pdf');
    const originalHTML = pdfBtn.innerHTML;
    pdfBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Generating PDF...';
    pdfBtn.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 = (pdfStartDate === 'All Dates' && pdfEndDate === 'All Dates')
                ? 'Period: All Dates'
                : `Period: ${pdfStartDate} To ${pdfEndDate}`;
            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 = `Sales_Report_${pdfStartDate}_to_${pdfEndDate}.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 {
        pdfBtn.innerHTML = originalHTML;
        pdfBtn.disabled = false;
    }
}

// Table search functionality
document.getElementById('tableSearch').addEventListener('keyup', function() {
    let searchValue = this.value.toLowerCase().trim();
    let rows = document.querySelectorAll('#salesTable tbody tr');
    
    rows.forEach(row => {
        if (row.querySelector('.empty-state')) return;
        let text = row.textContent.toLowerCase();
        row.style.display = text.includes(searchValue) ? '' : 'none';
    });
});
</script>

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