<?php
require_once 'config.php';
require_once 'auth_functions.php';
requireAdmin();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leave Reports - Leave Management System</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">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/dataTables.bootstrap5.min.css">
    <style>
        body { background-color: #f8f9fa; }
        .navbar { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }
    </style>
</head>
<body>
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="#"><i class="fas fa-calendar-check"></i> Leave Management System</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item"><a class="nav-link" href="admin_dashboard.php"><i class="fas fa-home"></i> Dashboard</a></li>
                    <li class="nav-item"><a class="nav-link" href="manage_employees.php"><i class="fas fa-users"></i> Employees</a></li>
                    <li class="nav-item"><a class="nav-link" href="approve_leaves.php"><i class="fas fa-check-circle"></i> Approve Leaves</a></li>
                    <li class="nav-item"><a class="nav-link active" href="leave_reports.php"><i class="fas fa-file-alt"></i> Reports</a></li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user-shield"></i> <?php echo $_SESSION['full_name']; ?>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>


    <div class="container mt-4">
        <h2 class="mb-4">Leave Reports & Downloads</h2>

        <div class="row">
            <!-- Employee Leave Report -->
            <div class="col-md-6 mb-4">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-user"></i> Individual Employee Leave Report</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Select Employee</label>
                            <select class="form-select" id="employee_select">
                                <option value="">Choose Employee...</option>
                                <?php
                                $sql = "SELECT * FROM users WHERE role = 'employee' ORDER BY full_name";
                                $result = $conn->query($sql);
                                while ($row = $result->fetch_assoc()):
                                ?>
                                <option value="<?php echo $row['id']; ?>">
                                    <?php echo $row['full_name'] . ' (' . $row['employee_id'] . ')'; ?>
                                </option>
                                <?php endwhile; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">Start Date</label>
                            <input type="date" class="form-control" id="emp_start_date">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">End Date</label>
                            <input type="date" class="form-control" id="emp_end_date">
                        </div>
                        <button class="btn btn-primary w-100" onclick="downloadEmployeeReport()">
                            <i class="fas fa-download"></i> Download Employee Report PDF
                        </button>
                    </div>
                </div>
            </div>

            <!-- All Employees Report -->
            <div class="col-md-6 mb-4">
                <div class="card">
                    <div class="card-header bg-success text-white">
                        <h5 class="mb-0"><i class="fas fa-users"></i> All Employees Leave Report</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">Start Date</label>
                            <input type="date" class="form-control" id="all_start_date">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">End Date</label>
                            <input type="date" class="form-control" id="all_end_date">
                        </div>
                        <button class="btn btn-success w-100" onclick="downloadAllReport()">
                            <i class="fas fa-download"></i> Download All Employees Report PDF
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- Leave Grid Report -->
        <div class="card mb-4">
            <div class="card-header bg-warning">
                <h5 class="mb-0"><i class="fas fa-table"></i> Leave Grid Report (All Employees)</h5>
            </div>
            <div class="card-body">
                <div class="row g-3 mb-3">
                    <div class="col-md-3">
                        <label class="form-label">Start Date</label>
                        <input type="date" class="form-control" id="grid_start_date">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">End Date (not counted)</label>
                        <input type="date" class="form-control" id="grid_end_date">
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button class="btn btn-warning w-100" onclick="viewLeaveGrid()">
                            <i class="fas fa-eye"></i> View Leave Grid
                        </button>
                    </div>
                    <div class="col-md-3 d-flex align-items-end">
                        <button class="btn btn-danger w-100" onclick="downloadLeaveGridPDF()">
                            <i class="fas fa-file-pdf"></i> Download PDF
                        </button>
                    </div>
                </div>
                <div class="table-responsive" id="leave_grid_container">
                    <!-- grid will be loaded here via AJAX -->
                </div>
            </div>
        </div>

        <!-- Leave Statistics Table -->
        <div class="card">
            <div class="card-header bg-info text-white">
                <h5 class="mb-0"><i class="fas fa-chart-bar"></i> Employee Leave Statistics</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="statsTable" class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Employee ID</th>
                                <th>Name</th>
                                <th>Department</th>
                                <th>Casual Used</th>
                                <th>Medical Used</th>
                                <th>Duty Used</th>
                                <th>Total Leaves</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $current_year = date('Y');
                            $sql = "SELECT u.*, 
                                    COALESCE(lb.casual_leaves_used, 0) AS casual_used,
                                    COALESCE(lb.medical_leaves_used, 0) AS medical_used,
                                    COALESCE(lb.duty_leaves_used, 0) AS duty_used
                                    FROM users u
                                    LEFT JOIN leave_balance lb 
                                        ON u.id = lb.user_id AND lb.year = $current_year
                                    WHERE u.role = 'employee'
                                    ORDER BY u.full_name";

                            $result = $conn->query($sql);

                            if (!$result) {
                                die('Query error: ' . $conn->error);
                            }

                            while ($row = $result->fetch_assoc()):
                                $total = $row['casual_used'] + $row['medical_used'] + $row['duty_used'];
                            ?>
                            <tr>
                                <td><?php echo $row['employee_id']; ?></td>
                                <td><?php echo $row['full_name']; ?></td>
                                <td><?php echo $row['department']; ?></td>
                                <td><?php echo $row['casual_used']; ?> / 20</td>
                                <td><?php echo $row['medical_used']; ?> / 21</td>
                                <td><?php echo $row['duty_used']; ?></td>
                                <td><strong><?php echo $total; ?></strong></td>
                                <td>
                                    <button class="btn btn-sm btn-primary" onclick="downloadSingleReport(<?php echo $row['id']; ?>)">
                                        <i class="fas fa-download"></i> PDF
                                    </button>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.13.6/js/dataTables.bootstrap5.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#statsTable').DataTable();
        });

        function downloadEmployeeReport() {
            const empId = $('#employee_select').val();
            const startDate = $('#emp_start_date').val();
            const endDate = $('#emp_end_date').val();
            
            if (!empId) {
                alert('Please select an employee');
                return;
            }
            
            window.open(`download_employee_report.php?user_id=${empId}&start_date=${startDate}&end_date=${endDate}`, '_blank');
        }

        function downloadAllReport() {
            const startDate = $('#all_start_date').val();
            const endDate = $('#all_end_date').val();
            
            window.open(`download_all_leaves_pdf.php?start_date=${startDate}&end_date=${endDate}`, '_blank');
        }

        function downloadSingleReport(userId) {
            window.open(`download_employee_report.php?user_id=${userId}`, '_blank');
        }

        // Load leave grid via AJAX
        function viewLeaveGrid() {
            const startDate = $('#grid_start_date').val();
            const endDate   = $('#grid_end_date').val();

            if (!startDate || !endDate) {
                alert('Please select both start and end dates');
                return;
            }

            $('#leave_grid_container').html('<div class="text-center py-3">Loading...</div>');

            $.get('leave-report.php', {
                start_date: startDate,
                end_date: endDate
            }, function(html) {
                $('#leave_grid_container').html(html);
            });
        }

        // Download leave grid as PDF
        function downloadLeaveGridPDF() {
            const startDate = $('#grid_start_date').val();
            const endDate   = $('#grid_end_date').val();

            if (!startDate || !endDate) {
                alert('Please select both start and end dates');
                return;
            }

            window.open(`download_leave_grid_pdf.php?start_date=${startDate}&end_date=${endDate}`, '_blank');
        }
    </script>
</body>
</html>
