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

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

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

// Filter variables
$filter_employee = isset($_GET['employee_id']) ? $_GET['employee_id'] : '';
$filter_entry_type = isset($_GET['entry_type']) ? $_GET['entry_type'] : '';
$filter_date_from = isset($_GET['date_from']) ? $_GET['date_from'] : '';
$filter_date_to = isset($_GET['date_to']) ? $_GET['date_to'] : '';

// Get all employees for filter dropdown
$employees_sql = "SELECT * FROM employees ORDER BY employee_name";
$employees_result = mysqli_query($conn, $employees_sql);

// Build WHERE clause for filters
$where_clauses = [];
if($filter_employee) {
    $where_clauses[] = "el.employee_id = '$filter_employee'";
}
if($filter_entry_type) {
    $where_clauses[] = "el.entry_type = '$filter_entry_type'";
}
if($filter_date_from) {
    $where_clauses[] = "DATE(el.date_time) >= '$filter_date_from'";
}
if($filter_date_to) {
    $where_clauses[] = "DATE(el.date_time) <= '$filter_date_to'";
}

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

// Get all ledger entries with filters
$ledger_sql = "SELECT el.*, e.employee_name, e.phone, e.designation, e.balance as current_balance
               FROM employee_ledger el
               LEFT JOIN employees e ON el.employee_id = e.id
               $where_sql
               ORDER BY el.id DESC";
$ledger_result = mysqli_query($conn, $ledger_sql);

// Calculate Summary Statistics
$total_entries = 0;
$total_salary = 0;
$total_advance = 0;
$total_bonus = 0;
$total_recovery = 0;
$net_amount = 0;

$ledger_data = [];
while($entry = mysqli_fetch_assoc($ledger_result)) {
    $ledger_data[] = $entry;
    $total_entries++;
    
    if($entry['entry_type'] == 'Salary') {
        $total_salary += $entry['amount'];
        $net_amount += $entry['amount'];
    } elseif($entry['entry_type'] == 'Advance') {
        $total_advance += $entry['amount'];
        $net_amount += $entry['amount'];
    } elseif($entry['entry_type'] == 'Bonus') {
        $total_bonus += $entry['amount'];
        $net_amount += $entry['amount'];
    } elseif($entry['entry_type'] == 'Recovery') {
        $total_recovery += $entry['amount'];
        $net_amount -= $entry['amount'];
    }
}
mysqli_data_seek($ledger_result, 0);

// Get employee summary if specific employee selected
$selected_employee_name = "";
$selected_employee_balance = 0;
$selected_employee_phone = "";
$selected_employee_designation = "";
if($filter_employee) {
    $emp_sql = "SELECT * FROM employees WHERE id = '$filter_employee'";
    $emp_result = mysqli_query($conn, $emp_sql);
    if($emp_data = mysqli_fetch_assoc($emp_result)) {
        $selected_employee_name = $emp_data['employee_name'];
        $selected_employee_balance = $emp_data['balance'];
        $selected_employee_phone = $emp_data['phone'];
        $selected_employee_designation = $emp_data['designation'];
    }
}

// Get overall employee statistics
$overall_stats_sql = "SELECT 
                       COUNT(id) as total_employees,
                       SUM(balance) as total_outstanding
                      FROM employees";
$overall_stats_result = mysqli_query($conn, $overall_stats_sql);
$overall_stats = mysqli_fetch_assoc($overall_stats_result);
$total_employees = $overall_stats['total_employees'] ? $overall_stats['total_employees'] : 0;
$total_outstanding = $overall_stats['total_outstanding'] ? $overall_stats['total_outstanding'] : 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>Employee Ledger Report</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- PDF Generation Libraries -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800&display=swap');
        
        * {
            font-family: 'Poppins', sans-serif;
        }
        
        h1, h2, h3, h4, h5, h6, .card-header h4, .table th {
            font-family: 'Times New Roman', serif;
        }
        
        body {
            background: #f5f5f5;
        }
        
        .main-container {
            padding: 20px;
        }
        
        /* Page Header */
        .page-header {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            border-radius: 15px;
            padding: 25px 30px;
            margin-bottom: 30px;
            color: #fff;
        }
        
        .page-header h2 {
            margin: 0 0 8px 0;
            font-size: 28px;
            color: #fff;
        }
        
        .page-header p {
            margin: 0;
            opacity: 0.95;
            font-weight: 500;
        }
        
        /* Stat Cards */
        .stat-card {
            background: #fff;
            border-radius: 15px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            border-left: 4px solid #A04657;
            transition: all 0.3s;
        }
        
        .stat-card:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 20px rgba(160,70,87,0.15);
        }
        
        .stat-icon {
            width: 50px;
            height: 50px;
            background: rgba(160,70,87,0.1);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 15px;
        }
        
        .stat-icon i {
            font-size: 24px;
            color: #A04657;
        }
        
        .stat-value {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 5px;
        }
        
        .stat-label {
            color: #666;
            font-size: 13px;
            font-weight: 500;
        }
        
        .stat-gain {
            color: #28a745;
        }
        
        .stat-loss {
            color: #dc3545;
        }
        
        /* Filter Card */
        .filter-card {
            background: #fff;
            border-radius: 15px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
        }
        
        .filter-header {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
        }
        
        .filter-header h5 {
            margin: 0;
            font-weight: 600;
            color: #333;
        }
        
        .filter-body {
            padding: 20px;
        }
        
        .filter-label {
            font-weight: 600;
            margin-bottom: 8px;
            color: #555;
            font-size: 13px;
        }
        
        .filter-label i {
            color: #A04657;
            margin-right: 5px;
        }
        
        .form-control, .form-select {
            border: 2px solid #e0e0e0;
            border-radius: 10px;
            padding: 8px 12px;
            font-weight: 500;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: #A04657;
            box-shadow: 0 0 0 3px rgba(160,70,87,0.1);
        }
        
        .btn-filter {
            background: linear-gradient(135deg, #A04657 0%, #6b2a36 100%);
            color: #fff;
            border: none;
            padding: 10px 25px;
            border-radius: 10px;
            font-weight: 600;
            margin-top: 30px;
            width: 100%;
        }
        
        .btn-filter:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(160,70,87,0.3);
            color: #fff;
        }
        
        .btn-reset {
            background: #6c757d;
            color: #fff;
            border: none;
            padding: 10px 25px;
            border-radius: 10px;
            font-weight: 600;
            margin-top: 30px;
            width: 100%;
        }
        
        .btn-reset:hover {
            background: #5a6268;
            color: #fff;
        }
        
        .btn-pdf, .btn-print {
            padding: 10px 20px;
            border-radius: 10px;
            font-weight: 600;
            cursor: pointer;
            border: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            font-size: 14px;
        }
        
        .btn-pdf {
            background: #dc3545;
            color: #fff;
        }
        
        .btn-pdf:hover {
            background: #c82333;
        }
        
        .btn-print {
            background: #17a2b8;
            color: #fff;
        }
        
        .btn-print:hover {
            background: #138496;
        }
        
        .btn-back {
            background: #A04657;
            color: #fff;
            text-decoration: none;
        }
        
        .btn-back:hover {
            background: #6b2a36;
            color: #fff;
        }
        
        /* Table Card */
        .table-card {
            background: #fff;
            border-radius: 15px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
        }
        
        .table-header {
            background: #f8f9fa;
            padding: 15px 20px;
            border-bottom: 1px solid #e0e0e0;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 15px;
        }
        
        .table-header h4 {
            margin: 0;
            font-weight: 600;
            color: #333;
        }
        
        .table-responsive {
            padding: 0;
        }
        
        .table {
            margin-bottom: 0;
        }
        
        .table th {
            background: #f8f9fa;
            font-weight: 700;
            color: #444;
            border-bottom: 2px solid #dee2e6;
            padding: 12px 15px;
        }
        
        .table td {
            padding: 12px 15px;
            vertical-align: middle;
            font-weight: 500;
        }
        
        .badge-salary {
            background: #17a2b8;
            color: #fff;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-advance {
            background: #ffc107;
            color: #856404;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-bonus {
            background: #28a745;
            color: #fff;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .badge-recovery {
            background: #dc3545;
            color: #fff;
            padding: 5px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 600;
        }
        
        .amount-positive {
            color: #28a745;
            font-weight: 700;
        }
        
        .amount-negative {
            color: #dc3545;
            font-weight: 700;
        }
        
        .employee-info-card {
            background: linear-gradient(135deg, #e8f5e9 0%, #c8e6c9 100%);
            border-radius: 12px;
            padding: 15px;
            margin-bottom: 20px;
            border-left: 4px solid #28a745;
        }
        
        .info-row {
            display: flex;
            justify-content: space-between;
            padding: 6px 0;
        }
        
        .info-row span {
            font-size: 13px;
            color: #2e7d32;
            font-weight: 500;
        }
        
        .info-row strong {
            font-size: 14px;
            color: #1b5e20;
            font-weight: 600;
        }
        
        .empty-state {
            text-align: center;
            padding: 50px;
        }
        
        .empty-state i {
            font-size: 64px;
            color: #ccc;
            margin-bottom: 20px;
        }
        
        .empty-state p {
            color: #666;
            font-weight: 500;
        }
        
        @media (max-width: 768px) {
            .main-container {
                padding: 15px;
            }
            
            .page-header {
                padding: 20px;
            }
            
            .page-header h2 {
                font-size: 22px;
            }
            
            .stat-value {
                font-size: 22px;
            }
            
            .table th, .table td {
                font-size: 12px;
                padding: 8px 10px;
            }
            
            .table-header {
                flex-direction: column;
            }
        }
        
        @media print {
            .filter-card, .btn-print, .btn-pdf, .page-header .btn {
                display: none !important;
            }
            
            .stat-card {
                break-inside: avoid;
            }
            
            .table-card {
                break-inside: avoid;
            }
            
            body {
                background: #fff;
                padding: 0;
                margin: 0;
            }
            
            .main-container {
                padding: 0;
            }
        }
    </style>
</head>
<body>
<div class="main-container">
    <div class="container-fluid">
        <!-- Page Header (Outside PDF Capture) -->
        <div class="page-header">
            <div class="d-flex justify-content-between align-items-center flex-wrap w-100">
                <div>
                    <h2><i class="fas fa-book"></i> Employee Ledger Report</h2>
                    <p>Track all employee salary transactions</p>
                </div>
                <div>
                    <button onclick="downloadPDF()" class="btn-pdf">
                        <i class="fas fa-file-pdf"></i> Download PDF
                    </button>
                    <button onclick="window.print()" class="btn-print ms-2">
                        <i class="fas fa-print"></i> Print Report
                    </button>
                    <a href="employee_ledger.php" class="btn-print btn-back ms-2">
                        <i class="fas fa-plus-circle"></i> Add Entry
                    </a>
                </div>
            </div>
        </div>

        <!-- Report Content (Captured for PDF) -->
        <div id="report-content-employee">
            <!-- Statistics Cards - Only 3 cards now -->
            <div class="row g-4 mb-4">
                <div class="col-md-4">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-history"></i>
                        </div>
                        <div class="stat-value"><?php echo $total_entries; ?></div>
                        <div class="stat-label">Total Transactions</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-money-bill-wave"></i>
                        </div>
                        <div class="stat-value stat-gain">Rs <?php echo number_format($total_salary, 2); ?></div>
                        <div class="stat-label">Total Salary</div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-users"></i>
                        </div>
                        <div class="stat-value">Rs <?php echo number_format($total_outstanding, 2); ?></div>
                        <div class="stat-label">Total Outstanding Balance</div>
                    </div>
                </div>
            </div>
            
            <!-- Second Row - Only Net Amount -->
            <div class="row g-4 mb-4">
                <div class="col-md-12">
                    <div class="stat-card">
                        <div class="stat-icon">
                            <i class="fas fa-calculator"></i>
                        </div>
                        <div class="stat-value <?php echo $net_amount >= 0 ? 'stat-gain' : 'stat-loss'; ?>">
                            Rs <?php echo number_format(abs($net_amount), 2); ?>
                            <small style="font-size: 12px;"><?php echo $net_amount >= 0 ? '(Net Paid)' : '(Net Recovered)'; ?></small>
                        </div>
                        <div class="stat-label">Net Amount</div>
                    </div>
                </div>
            </div>
            
            <!-- Employee Info Card (if specific employee selected) -->
            <?php if($filter_employee && $selected_employee_name): ?>
                <div class="employee-info-card mb-4">
                    <div class="info-row">
                        <span><i class="fas fa-user"></i> Employee Name:</span>
                        <strong><?php echo htmlspecialchars($selected_employee_name); ?></strong>
                    </div>
                    <div class="info-row">
                        <span><i class="fas fa-phone"></i> Phone:</span>
                        <strong><?php echo htmlspecialchars($selected_employee_phone); ?></strong>
                    </div>
                    <div class="info-row">
                        <span><i class="fas fa-briefcase"></i> Designation:</span>
                        <strong><?php echo htmlspecialchars($selected_employee_designation); ?></strong>
                    </div>
                    <div class="info-row">
                        <span><i class="fas fa-rupee-sign"></i> Current Balance:</span>
                        <strong style="color: #A04657;">Rs <?php echo number_format($selected_employee_balance, 2); ?></strong>
                    </div>
                </div>
            <?php endif; ?>
            
            <!-- Employee Ledger Table -->
            <div class="table-card">
                <div class="table-header">
                    <h4><i class="fas fa-list"></i> Employee Ledger Transactions</h4>
                    <div>
                        <span class="text-muted">
                            <i class="fas fa-database"></i> Total Records: <?php echo $total_entries; ?>
                        </span>
                    </div>
                </div>
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>#ID</th>
                                <th>Employee</th>
                                <th>Designation</th>
                                <th>Entry Type</th>
                                <th>Amount</th>
                                <th>Description</th>
                                <th>Date & Time</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(count($ledger_data) > 0): ?>
                                <?php foreach($ledger_data as $entry): ?>
                                    <tr>
                                        <td>#<?php echo $entry['id']; ?></td>
                                        <td>
                                            <strong><?php echo htmlspecialchars($entry['employee_name']); ?></strong>
                                        </td>
                                        <td><?php echo htmlspecialchars($entry['designation']); ?></div>
                                        <td>
                                            <?php if($entry['entry_type'] == 'Salary'): ?>
                                                <span class="badge-salary"><i class="fas fa-money-bill-wave"></i> Salary</span>
                                            <?php elseif($entry['entry_type'] == 'Advance'): ?>
                                                <span class="badge-advance"><i class="fas fa-hand-holding-usd"></i> Advance</span>
                                            <?php elseif($entry['entry_type'] == 'Bonus'): ?>
                                                <span class="badge-bonus"><i class="fas fa-gift"></i> Bonus</span>
                                            <?php else: ?>
                                                <span class="badge-recovery"><i class="fas fa-undo-alt"></i> Recovery</span>
                                            <?php endif; ?>
                                        </div>
                                        <td class="<?php echo ($entry['entry_type'] != 'Recovery') ? 'amount-positive' : 'amount-negative'; ?>">
                                            <?php echo ($entry['entry_type'] != 'Recovery') ? '+' : '-'; ?> Rs <?php echo number_format($entry['amount'], 2); ?>
                                        </div>
                                        <td>
                                            <?php echo htmlspecialchars($entry['description'] ?: '—'); ?>
                                        </div>
                                        <td>
                                            <i class="fas fa-calendar-alt"></i> <?php echo date('d-m-Y', strtotime($entry['date_time'])); ?>
                                            <br>
                                            <small><i class="fas fa-clock"></i> <?php echo date('h:i A', strtotime($entry['date_time'])); ?></small>
                                        </div>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" class="empty-state">
                                        <i class="fas fa-book"></i>
                                        <p>No employee ledger records found</p>
                                        <small class="text-muted">Try changing filters or add new ledger entries</small>
                                    </div>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            
            <!-- Summary by Employee (when no specific employee selected) -->
            <?php if(!$filter_employee && $total_entries > 0): ?>
            <div class="table-card mt-4">
                <div class="table-header">
                    <h4><i class="fas fa-chart-pie"></i> Summary by Employee</h4>
                </div>
                <div class="table-responsive">
    <table class="table table-hover">
        <thead>
            <tr>
                <th>Employee</th>
                <th>Designation</th>
                <th>Total Salary</th>
                <th>Net Paid</th>
                <th>Current Balance</th>
            </thead>
        <tbody>
            <?php
            // Group by employee
            $employee_summary = [];
            foreach($ledger_data as $entry) {
                $emp_id = $entry['employee_id'];
                if(!isset($employee_summary[$emp_id])) {
                    $employee_summary[$emp_id] = [
                        'name' => $entry['employee_name'],
                        'designation' => $entry['designation'],
                        'salary' => 0,
                        'advance' => 0,
                        'bonus' => 0,
                        'recovery' => 0,
                        'current_balance' => $entry['current_balance']
                    ];
                }
                
                if($entry['entry_type'] == 'Salary') {
                    $employee_summary[$emp_id]['salary'] += $entry['amount'];
                } elseif($entry['entry_type'] == 'Advance') {
                    $employee_summary[$emp_id]['advance'] += $entry['amount'];
                } elseif($entry['entry_type'] == 'Bonus') {
                    $employee_summary[$emp_id]['bonus'] += $entry['amount'];
                } elseif($entry['entry_type'] == 'Recovery') {
                    $employee_summary[$emp_id]['recovery'] += $entry['amount'];
                }
            }
            
            foreach($employee_summary as $emp):
                $net_paid = $emp['salary'] + $emp['advance'] + $emp['bonus'] - $emp['recovery'];
            ?>
                <tr>
                    <td><strong><?php echo htmlspecialchars($emp['name']); ?></strong></td>
                    <td><?php echo htmlspecialchars($emp['designation']); ?></td>
                    <td class="amount-positive">Rs <?php echo number_format($emp['salary'], 2); ?></td>
                    <td class="<?php echo $net_paid >= 0 ? 'amount-positive' : 'amount-negative'; ?>">
                        Rs <?php echo number_format(abs($net_paid), 2); ?>
                        <?php echo $net_paid >= 0 ? '(Paid)' : '(Recovered)'; ?>
                    </td>
                    <td style="color: #A04657; font-weight: 700;">
                        Rs <?php echo number_format($emp['current_balance'], 2); ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>
            </div>
            <?php endif; ?>
        </div><!-- end #report-content-employee -->

        <!-- Filter Card (Outside PDF Capture) -->
        <div class="filter-card mt-4">
            <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> Employee</label>
                            <select name="employee_id" class="form-select">
                                <option value="">-- All Employees --</option>
                                <?php 
                                mysqli_data_seek($employees_result, 0);
                                while($emp = mysqli_fetch_assoc($employees_result)): 
                                    $selected = ($filter_employee == $emp['id']) ? 'selected' : '';
                                ?>
                                    <option value="<?php echo $emp['id']; ?>" <?php echo $selected; ?>>
                                        <?php echo htmlspecialchars($emp['employee_name']); ?> (<?php echo htmlspecialchars($emp['designation']); ?>)
                                    </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="filter-label"><i class="fas fa-tag"></i> Entry Type</label>
                            <select name="entry_type" class="form-select">
                                <option value="">-- All Types --</option>
                                <option value="Salary" <?php echo $filter_entry_type == 'Salary' ? 'selected' : ''; ?>>Salary</option>
                                <option value="Advance" <?php echo $filter_entry_type == 'Advance' ? 'selected' : ''; ?>>Advance</option>
                                <option value="Bonus" <?php echo $filter_entry_type == 'Bonus' ? 'selected' : ''; ?>>Bonus</option>
                                <option value="Recovery" <?php echo $filter_entry_type == 'Recovery' ? 'selected' : ''; ?>>Recovery</option>
                            </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 class="col-md-1">
                            <a href="employee_ledger_report.php" class="btn-reset d-block text-center">
                                <i class="fas fa-undo-alt"></i> Reset
                            </a>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
// Pass filter info to JS for PDF header
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 = 'Employee Ledger Report';

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

        // ── 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 = `Employee_Ledger_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;
    }
}

// Auto-submit when filter changes (if needed)
document.querySelectorAll('.filter-auto').forEach(function(element) {
    element.addEventListener('change', function() {
        this.closest('form').submit();
    });
});
</script>

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