<?php
require_once 'config.php';
require_once 'auth_functions.php';
requireAdmin();

// Handle delete request with balance adjustment
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_leave_id'])) {
    $leave_id = (int)$_POST['delete_leave_id'];

    // Load leave details
    $sql = "SELECT * FROM leave_applications WHERE id = $leave_id";
    $res = $conn->query($sql);
    if ($res && $res->num_rows > 0) {
        $leave = $res->fetch_assoc();

        // If approved, reverse its effect from leave_balance / short_leave_tracking
        if ($leave['status'] === 'approved') {
            $user_id        = (int)$leave['user_id'];
            $year           = (int)$leave['year'];
            $leave_type     = $leave['leave_type'];       // casual / medical / duty / short
            $number_of_days = (float)$leave['number_of_days'];

            // Ensure leave_balance row exists
            $sql_balance = "SELECT * FROM leave_balance WHERE user_id = $user_id AND year = $year";
            $bal_res = $conn->query($sql_balance);
            if ($bal_res->num_rows === 0) {
                $conn->query("INSERT INTO leave_balance (user_id, year) VALUES ($user_id, $year)");
                $bal_res = $conn->query($sql_balance);
            }

            // Decrement appropriate used field (not going below 0)
            if (in_array($leave_type, ['casual','medical','duty'])) {
                $field_map = [
                    'casual' => 'casual_leaves_used',
                    'medical'=> 'medical_leaves_used',
                    'duty'   => 'duty_leaves_used',
                ];
                $field = $field_map[$leave_type];

                $sql_update_balance = "
                    UPDATE leave_balance
                    SET $field = GREATEST($field - $number_of_days, 0)
                    WHERE user_id = $user_id AND year = $year
                ";
                $conn->query($sql_update_balance);
            }

            // If short leave, also reduce short_leave_tracking count
            if ($leave_type === 'short') {
                $month = (int)$leave['month'];
                $sql_short = "
                    UPDATE short_leave_tracking
                    SET short_leaves_count = GREATEST(short_leaves_count - 1, 0)
                    WHERE user_id = $user_id AND year = $year AND month = $month
                ";
                $conn->query($sql_short);
            }
        }

        // Now delete the leave application
        $sql_delete = "DELETE FROM leave_applications WHERE id = $leave_id";
        if ($conn->query($sql_delete)) {
            $message = "Leave application deleted and balances adjusted.";
        } else {
            $error = "Error deleting leave: " . $conn->error;
        }
    } else {
        $error = "Leave record not found.";
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>All Leaves Table - 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" 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-fluid mt-4">
        <h2 class="mb-4">All Leave Applications</h2>

        <?php if (!empty($message)): ?>
            <div class="alert alert-success alert-dismissible fade show">
                <?php echo $message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if (!empty($error)): ?>
            <div class="alert alert-danger alert-dismissible fade show">
                <?php echo $error; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="fas fa-filter"></i> Filter Options</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <label>Start Date</label>
                        <input type="date" id="filter_start" class="form-control">
                    </div>
                    <div class="col-md-3">
                        <label>End Date</label>
                        <input type="date" id="filter_end" class="form-control">
                    </div>
                    <div class="col-md-3">
                        <label>Status</label>
                        <select class="form-select" id="filter_status">
                            <option value="">All Status</option>
                            <option value="pending">Pending</option>
                            <option value="approved">Approved</option>
                            <option value="rejected">Rejected</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label>&nbsp;</label>
                        <button class="btn btn-primary w-100 mb-2" onclick="filterTable()">
                            <i class="fas fa-search"></i> Apply Filter
                        </button>
                        <button class="btn btn-success w-100" onclick="downloadPDF()">
                            <i class="fas fa-download"></i> Download PDF
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <div class="card">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0"><i class="fas fa-table"></i> Leave Applications Data</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="allLeavesTable" class="table table-striped table-hover table-sm">
                        <thead>
                            <tr>
                                <th>Employee ID</th>
                                <th>Employee Name</th>
                                <th>Department</th>
                                <th>Leave Type</th>
                                <th>Start Date</th>
                                <th>End Date</th>
                                <th>Days</th>
                                <th>Reason</th>
                                <th>Status</th>
                                <th>Applied Date</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $sql = "SELECT la.*, u.full_name, u.employee_id as emp_id, u.department 
                                    FROM leave_applications la
                                    JOIN users u ON la.user_id = u.id
                                    ORDER BY la.apply_date DESC";
                            $result = $conn->query($sql);
                            while ($row = $result->fetch_assoc()):
                            ?>
                            <tr>
                                <td><?php echo $row['emp_id']; ?></td>
                                <td><?php echo $row['full_name']; ?></td>
                                <td><?php echo $row['department']; ?></td>
                                <td><?php echo ucfirst($row['leave_type']); ?></td>
                                <td><?php echo date('Y-m-d', strtotime($row['start_date'])); ?></td>
                                <td><?php echo date('Y-m-d', strtotime($row['end_date'])); ?></td>
                                <td><?php echo $row['number_of_days']; ?></td>
                                <td><?php echo substr($row['reason'], 0, 50); ?></td>
                                <td>
                                    <?php
                                    $badge = $row['status'] === 'approved'
                                             ? 'success'
                                             : ($row['status'] === 'rejected' ? 'danger' : 'warning');
                                    echo "<span class='badge bg-{$badge}'>" . ucfirst($row['status']) . "</span>";
                                    ?>
                                </td>
                                <td><?php echo date('Y-m-d H:i', strtotime($row['apply_date'])); ?></td>
                                <td>
                                    <form method="POST" action=""
                                          onsubmit="return confirm('Are you sure you want to delete this leave? This will also adjust the leave balance.');">
                                        <input type="hidden" name="delete_leave_id" value="<?php echo $row['id']; ?>">
                                        <button type="submit" class="btn btn-sm btn-outline-danger">
                                            <i class="fas fa-trash"></i> Delete
                                        </button>
                                    </form>
                                </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>
        let table;
        
        $(document).ready(function() {
            table = $('#allLeavesTable').DataTable({
                pageLength: 25,
                order: [[9, 'desc']]
            });
        });

        function filterTable() {
            // Currently this only reinitializes DataTable; real filtering would require
            // server-side or client-side logic over the rows.
            table.destroy();
            table = $('#allLeavesTable').DataTable({
                pageLength: 25,
                order: [[9, 'desc']]
            });
        }

        function downloadPDF() {
            const startDate = $('#filter_start').val();
            const endDate = $('#filter_end').val();
            window.open(`download_all_leaves_pdf.php?start_date=${startDate}&end_date=${endDate}`, '_blank');
        }
    </script>
</body>
</html>
