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

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

$success_message = "";
$error_message = "";

// Filter variables
$filter_customer = isset($_GET['customer_id']) ? $_GET['customer_id'] : '';
$filter_fuel_type = isset($_GET['fuel_type_id']) ? $_GET['fuel_type_id'] : '';
$filter_date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$filter_date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Get all customers for filter dropdown
$customers_sql = "SELECT id, name, vehicle_no FROM customers ORDER BY name";
$customers_result = mysqli_query($conn, $customers_sql);

// Get all fuel types for filter dropdown
$fuel_types_sql = "SELECT id, name FROM fuel_types ORDER BY name";
$fuel_types_result = mysqli_query($conn, $fuel_types_sql);

// Build WHERE clause for filters
$where_clauses = [];
if($filter_customer) {
    $where_clauses[] = "cs.customer_id = '$filter_customer'";
}
if($filter_fuel_type) {
    $where_clauses[] = "cs.fuel_type_id = '$filter_fuel_type'";
}
if($filter_date_from) {
    $where_clauses[] = "DATE(cs.date_time) >= '$filter_date_from'";
}
if($filter_date_to) {
    $where_clauses[] = "DATE(cs.date_time) <= '$filter_date_to'";
}

$where_sql = !empty($where_clauses) ? "WHERE " . implode(" AND ", $where_clauses) : "";

// Get all credit sales with filters
$sql = "SELECT cs.*, c.name as customer_name, c.vehicle_no, c.phone, c.balance as customer_balance, 
               c.advance_balance as customer_advance, s.shift_name, ft.name as fuel_name, ft.sale_price
        FROM credit_sales cs
        LEFT JOIN customers c ON cs.customer_id = c.id
        LEFT JOIN shift_entries s ON cs.shift_id = s.id
        LEFT JOIN fuel_types ft ON cs.fuel_type_id = ft.id
        $where_sql
        ORDER BY cs.id DESC";
$result = mysqli_query($conn, $sql);

// Calculate Summary Statistics
$total_records = 0;
$total_amount = 0;
$total_liters = 0;
$total_advance_used = 0;
$net_payable_total = 0;

$credit_data = [];
while($row = mysqli_fetch_assoc($result)) {
    $credit_data[] = $row;
    $total_records++;
    $total_amount += $row['amount'];
    $total_liters += $row['liters'];
    $total_advance_used += $row['advance_used'];
    $net_payable_total += ($row['amount'] - $row['advance_used']);
}
mysqli_data_seek($result, 0);

// Get customer-wise summary
$customer_summary = [];
foreach($credit_data as $row) {
    $cust_id = $row['customer_id'];
    if(!isset($customer_summary[$cust_id])) {
        $customer_summary[$cust_id] = [
            'name' => $row['customer_name'],
            'vehicle' => $row['vehicle_no'],
            'total_amount' => 0,
            'total_liters' => 0,
            'advance_used' => 0,
            'net_payable' => 0
        ];
    }
    $customer_summary[$cust_id]['total_amount'] += $row['amount'];
    $customer_summary[$cust_id]['total_liters'] += $row['liters'];
    $customer_summary[$cust_id]['advance_used'] += $row['advance_used'];
    $customer_summary[$cust_id]['net_payable'] += ($row['amount'] - $row['advance_used']);
}

// Get fuel-wise summary
$fuel_summary = [];
foreach($credit_data as $row) {
    $fuel_id = $row['fuel_type_id'];
    if(!isset($fuel_summary[$fuel_id])) {
        $fuel_summary[$fuel_id] = [
            'name' => $row['fuel_name'],
            'total_amount' => 0,
            'total_liters' => 0
        ];
    }
    $fuel_summary[$fuel_id]['total_amount'] += $row['amount'];
    $fuel_summary[$fuel_id]['total_liters'] += $row['liters'];
}
?>

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

<div class="report-container">
    <!-- Page Header -->
    <div class="page-header">
        <div>
            <h2><i class="fas fa-file-invoice-dollar"></i> Credit Sales Report</h2>
            <p>Complete credit sales history with customer and fuel wise summary</p>
        </div>
        <div class="header-actions">
            <button onclick="window.print()" class="btn-print">
                <i class="fas fa-print"></i> Print Report
            </button>
            <button onclick="downloadPDF()" class="btn-pdf">
                <i class="fas fa-file-pdf"></i> Download PDF
            </button>
            <a href="credit_sales.php" class="btn-back">
                <i class="fas fa-arrow-left"></i> Back to Credit Sales
            </a>
        </div>
    </div>
    
    <!-- Filter Card -->
    <div class="filter-card">
        <div class="filter-header">
            <h5><i class="fas fa-filter"></i> Filter Reports</h5>
        </div>
        <div class="filter-body">
            <form method="GET" action="">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="filter-label"><i class="fas fa-user"></i> Customer</label>
                        <select name="customer_id" class="form-select">
                            <option value="">-- All Customers --</option>
                            <?php 
                            mysqli_data_seek($customers_result, 0);
                            while($cust = mysqli_fetch_assoc($customers_result)): 
                                $selected = ($filter_customer == $cust['id']) ? 'selected' : '';
                            ?>
                                <option value="<?php echo $cust['id']; ?>" <?php echo $selected; ?>>
                                    <?php echo htmlspecialchars($cust['name']); ?> (<?php echo $cust['vehicle_no']; ?>)
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <label class="filter-label"><i class="fas fa-gas-pump"></i> Fuel Type</label>
                        <select name="fuel_type_id" class="form-select">
                            <option value="">-- All Fuels --</option>
                            <?php 
                            mysqli_data_seek($fuel_types_result, 0);
                            while($fuel = mysqli_fetch_assoc($fuel_types_result)): 
                                $selected = ($filter_fuel_type == $fuel['id']) ? 'selected' : '';
                            ?>
                                <option value="<?php echo $fuel['id']; ?>" <?php echo $selected; ?>>
                                    <?php echo $fuel['name']; ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="filter-label"><i class="fas fa-calendar-alt"></i> Date From</label>
                        <input type="date" name="date_from" class="form-control" value="<?php echo $filter_date_from; ?>">
                    </div>
                    <div class="col-md-3">
                        <label class="filter-label"><i class="fas fa-calendar-alt"></i> Date To</label>
                        <input type="date" name="date_to" class="form-control" value="<?php echo $filter_date_to; ?>">
                    </div>
                    <div class="col-md-1">
                        <button type="submit" class="btn-filter">
                            <i class="fas fa-search"></i> Filter
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Report Content for PDF capture -->
    <div id="report-content-credit">
        <!-- Statistics Cards -->
        <div class="stats-row">
            <div class="stat-card">
                <div class="stat-icon"><i class="fas fa-chart-line"></i></div>
                <div class="stat-info">
                    <h3><?php echo $total_records; ?></h3>
                    <p>Total Transactions</p>
                </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_liters, 2); ?> L</h3>
                    <p>Total Liters Sold</p>
                </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_amount, 2); ?></h3>
                    <p>Total Credit Amount</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon"><i class="fas fa-hand-holding-usd"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($total_advance_used, 2); ?></h3>
                    <p>Advance Used</p>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon"><i class="fas fa-calculator"></i></div>
                <div class="stat-info">
                    <h3>Rs <?php echo number_format($net_payable_total, 2); ?></h3>
                    <p>Net Payable</p>
                </div>
            </div>
        </div>
        
        <!-- Customer Wise Summary -->
        <?php if(!$filter_customer && count($customer_summary) > 0): ?>
        <div class="summary-card">
            <div class="card-header-custom">
                <h4><i class="fas fa-chart-pie"></i> Customer Wise Summary</h4>
            </div>
            <div class="card-body-custom">
                <div class="summary-grid">
                    <?php foreach($customer_summary as $cust): ?>
                        <div class="summary-item">
                            <div class="summary-item-title"><?php echo htmlspecialchars($cust['name']); ?></div>
                            <div class="summary-item-row">
                                <span>Vehicle:</span>
                                <span><?php echo htmlspecialchars($cust['vehicle']); ?></span>
                            </div>
                            <div class="summary-item-row">
                                <span>Total Liters:</span>
                                <span><?php echo number_format($cust['total_liters'], 2); ?> L</span>
                            </div>
                            <div class="summary-item-row">
                                <span>Total Amount:</span>
                                <span>Rs <?php echo number_format($cust['total_amount'], 2); ?></span>
                            </div>
                            <div class="summary-item-row">
                                <span>Advance Used:</span>
                                <span>Rs <?php echo number_format($cust['advance_used'], 2); ?></span>
                            </div>
                            <div class="summary-item-row">
                                <span><strong>Net Payable:</strong></span>
                                <span><strong>Rs <?php echo number_format($cust['net_payable'], 2); ?></strong></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Fuel Wise Summary -->
        <?php if(!$filter_fuel_type && count($fuel_summary) > 0): ?>
        <div class="summary-card">
            <div class="card-header-custom">
                <h4><i class="fas fa-chart-line"></i> Fuel Wise Summary</h4>
            </div>
            <div class="card-body-custom">
                <div class="summary-grid">
                    <?php foreach($fuel_summary as $fuel): ?>
                        <div class="summary-item">
                            <div class="summary-item-title"><?php echo htmlspecialchars($fuel['name']); ?></div>
                            <div class="summary-item-row">
                                <span>Total Liters:</span>
                                <span><?php echo number_format($fuel['total_liters'], 2); ?> L</span>
                            </div>
                            <div class="summary-item-row">
                                <span>Total Amount:</span>
                                <span>Rs <?php echo number_format($fuel['total_amount'], 2); ?></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>
        
        <!-- Credit Sales Table -->
        <div class="table-card">
            <div class="table-header">
                <h4><i class="fas fa-list"></i> Credit Sales Details</h4>
                <div class="table-search">
                    <i class="fas fa-search"></i>
                    <input type="text" id="tableSearch" placeholder="Search..." class="search-input">
                </div>
            </div>
            <div class="table-responsive">
                <table class="credit-table" id="creditTable">
                    <thead>
                        <tr>
                            <th>#</th>
                            <th>Date & Time</th>
                            <th>Customer</th>
                            <th>Vehicle</th>
                            <th>Fuel Type</th>
                            <th>Shift</th>
                            <th>Liters</th>
                            <th>Amount (Rs)</th>
                            <th>Advance Used</th>
                            <th>Net Payable</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(count($credit_data) > 0): ?>
                            <?php $sn = 1; foreach($credit_data as $row): ?>
                                <tr>
                                    <td data-label="#"><?php echo $sn++; ?></td>
                                    <td data-label="Date & Time"><?php echo date('d-m-Y H:i', strtotime($row['date_time'])); ?></td>
                                    <td data-label="Customer"><strong><?php echo htmlspecialchars($row['customer_name']); ?></strong></td>
                                    <td data-label="Vehicle"><?php echo htmlspecialchars($row['vehicle_no']); ?></td>
                                    <td data-label="Fuel Type"><span class="fuel-badge"><?php echo $row['fuel_name']; ?></span></td>
                                    <td data-label="Shift"><span class="shift-badge"><?php echo $row['shift_name']; ?></span></td>
                                    <td data-label="Liters" class="liters-value"><?php echo number_format($row['liters'], 2); ?> L</div>
                                    <td data-label="Amount" class="amount-value">Rs <?php echo number_format($row['amount'], 2); ?></div>
                                    <td data-label="Advance Used" class="advance-value">
                                        <?php if($row['advance_used'] > 0): ?>
                                            Rs <?php echo number_format($row['advance_used'], 2); ?>
                                        <?php else: ?>
                                            —
                                        <?php endif; ?>
                                    </div>
                                    <td data-label="Net Payable" class="net-value">
                                        Rs <?php echo number_format($row['amount'] - $row['advance_used'], 2); ?>
                                    </div>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr>
                                <td colspan="10" class="empty-state">
                                    <i class="fas fa-inbox"></i>
                                    <p>No credit sales records found</p>
                                    <small>Try changing filters or add new credit sales</small>
                                </div>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                    <tfoot>
                        <tr class="totals-row">
                            <td colspan="6" style="text-align: right;"><strong>Total:</strong></div>
                            <td class="liters-value"><strong><?php echo number_format($total_liters, 2); ?> L</strong></div>
                            <td class="amount-value"><strong>Rs <?php echo number_format($total_amount, 2); ?></strong></div>
                            <td class="advance-value"><strong>Rs <?php echo number_format($total_advance_used, 2); ?></strong></div>
                            <td class="net-value"><strong>Rs <?php echo number_format($net_payable_total, 2); ?></strong></div>
                        </tr>
                    </tfoot>
                </table>
            </div>
        </div>
    </div><!-- end report-content-credit -->
</div>

<style>
/* Credit Sales Report Styles - Page Specific Only */
@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&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,
.stat-info h3,
.card-header-custom h4,
.credit-table th {
    font-family: 'Poppins', sans-serif;
    font-weight: 600;
}

/* Main Content */
.main-content {
    margin-left: 280px;
    padding: 15px 20px;
    transition: all 0.3s;
    background: #f5f7fb;
}

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

/* Page Header */
.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;
}

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

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

.btn-print {
    background: rgba(255,255,255,0.2);
}

.btn-print:hover {
    background: rgba(255,255,255,0.3);
}

.btn-pdf {
    background: #dc3545;
}

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

.btn-back {
    background: #6c757d;
}

.btn-back:hover {
    background: #5a6268;
    color: #fff;
}

/* Filter Card */
.filter-card {
    background: #fff;
    border-radius: 16px;
    margin-bottom: 20px;
    border: 1px solid #f0f0f0;
    width: 100%;
}

.filter-header {
    background: #f8f9fa;
    padding: 12px 20px;
    border-bottom: 1px solid #e0e0e0;
}

.filter-header h5 {
    margin: 0;
    font-weight: 600;
    color: #333;
    font-size: 14px;
}

.filter-body {
    padding: 16px;
}

.filter-label {
    font-weight: 600;
    margin-bottom: 6px;
    color: #555;
    font-size: 12px;
}

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

.form-control, .form-select {
    border: 2px solid #e0e0e0;
    border-radius: 10px;
    padding: 8px 12px;
    font-weight: 500;
    font-size: 13px;
    width: 100%;
}

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

.btn-filter {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    color: #fff;
    border: none;
    padding: 8px 16px;
    border-radius: 10px;
    font-weight: 600;
    margin-top: 28px;
    width: 100%;
    font-size: 13px;
}

.btn-filter:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(160,70,87,0.3);
    color: #fff;
}

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

.stat-card {
    background: #fff;
    border-radius: 16px;
    padding: 16px;
    display: flex;
    align-items: center;
    gap: 14px;
    border: 1px solid #f0f0f0;
}

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

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

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

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

/* Summary Cards */
.summary-card {
    background: #fff;
    border-radius: 16px;
    margin-bottom: 20px;
    border: 1px solid #f0f0f0;
    width: 100%;
}

.card-header-custom {
    background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
    padding: 12px 20px;
    color: #fff;
}

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

.card-body-custom {
    padding: 16px;
}

.summary-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
    gap: 12px;
}

.summary-item {
    background: #f8f9fa;
    border-radius: 12px;
    padding: 10px 14px;
    border-left: 3px solid #A04657;
}

.summary-item-title {
    font-weight: 700;
    font-size: 13px;
    margin-bottom: 6px;
    color: #333;
}

.summary-item-row {
    display: flex;
    justify-content: space-between;
    font-size: 11px;
    padding: 3px 0;
}

.summary-item-row strong {
    color: #A04657;
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 16px;
    border: 1px solid #f0f0f0;
    width: 100%;
}

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

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

.table-search {
    position: relative;
}

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

.search-input {
    padding: 8px 12px 8px 36px;
    border: 2px solid #e0e0e0;
    border-radius: 30px;
    width: 200px;
    font-size: 12px;
}

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

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

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

.credit-table th {
    padding: 10px 12px;
    background: #f8f9fa;
    font-weight: 700;
    color: #444;
    font-size: 11px;
    border-bottom: 2px solid #e8e8e8;
}

.credit-table td {
    padding: 10px 12px;
    border-bottom: 1px solid #f0f0f0;
    font-size: 12px;
    color: #444;
    vertical-align: middle;
}

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

.fuel-badge {
    background: #e3f2fd;
    color: #1565c0;
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 600;
    display: inline-block;
}

.shift-badge {
    background: #e8f5e9;
    color: #2e7d32;
    padding: 3px 8px;
    border-radius: 20px;
    font-size: 10px;
    font-weight: 600;
    display: inline-block;
}

.amount-value {
    color: #dc3545;
    font-weight: 700;
}

.advance-value {
    color: #17a2b8;
    font-weight: 600;
}

.net-value {
    color: #28a745;
    font-weight: 700;
}

.liters-value {
    color: #ff9800;
    font-weight: 600;
}

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

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

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

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

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

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

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

/* Print Styles */
@media print {
    .sidebar, .top-header, .footer, .filter-card, .btn-print, .btn-back, .btn-pdf, .table-search {
        display: none !important;
    }
    .main-content {
        margin: 0;
        padding: 0;
        width: 100%;
    }
    .stat-card {
        break-inside: avoid;
    }
    .credit-table {
        font-size: 10px;
    }
}

/* 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>

<!-- 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>

<script>
const pdfDateFrom = '<?php echo $filter_date_from ? date('d-m-Y', strtotime($filter_date_from)) : "All Dates"; ?>';
const pdfDateTo = '<?php echo $filter_date_to ? date('d-m-Y', strtotime($filter_date_to)) : "All Dates"; ?>';
const reportTitle = 'Credit Sales Report';

async function downloadPDF() {
    const element = document.getElementById('report-content-credit');
    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 {
        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;

        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 = (pdfDateFrom === 'All Dates' && pdfDateTo === 'All Dates')
                ? 'Period: All Dates'
                : `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);
        }

        let remainingMM = totalImgHeightMM;
        let sourceYpx = 0;
        addHeader();

        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 = `Credit_Sales_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 {
        pdfBtn.innerHTML = originalHTML;
        pdfBtn.disabled = false;
    }
}

// Table search
document.getElementById('tableSearch')?.addEventListener('keyup', function() {
    let searchValue = this.value.toLowerCase();
    let table = document.getElementById('creditTable');
    let rows = table.getElementsByTagName('tr');
    
    for (let i = 1; i < rows.length - 1; i++) {
        let row = rows[i];
        let text = row.textContent.toLowerCase();
        row.style.display = text.includes(searchValue) ? '' : 'none';
    }
});
</script>

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