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

$admin_role = $_SESSION['role'];
$admin_id   = $_SESSION['user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $leave_id       = (int)$_POST['leave_id'];
    $action         = $_POST['action'];
    $new_leave_type = $_POST['new_leave_type'] ?? null;

    // Get leave application details
    $sql = "SELECT la.*, lb.casual_leaves_used, lb.medical_leaves_used, lb.duty_leaves_used 
            FROM leave_applications la
            LEFT JOIN leave_balance lb ON la.user_id = lb.user_id AND la.year = lb.year
            WHERE la.id = $leave_id";
    $result = $conn->query($sql);
    $leave  = $result ? $result->fetch_assoc() : null;

    if (!$leave) {
        echo json_encode(['success' => false, 'message' => 'Leave record not found.']);
        exit;
    }

    // Total approved leaves for this employee in current year
    $sql_total = "SELECT SUM(number_of_days) as total FROM leave_applications 
                  WHERE user_id = {$leave['user_id']} 
                    AND status = 'approved' 
                    AND year = {$leave['year']}";
    $total_result = $conn->query($sql_total);
    $total_row    = $total_result ? $total_result->fetch_assoc() : ['total' => 0];
    $total_leaves = $total_row['total'] ?? 0;

    if ($action === 'approve') {
        // Check approval limit
        if (!canApproveLeave($admin_role, $total_leaves)) {
            echo json_encode(['success' => false, 'message' => 'You do not have authority to approve this leave.']);
            exit;
        }

        // Change leave type if principal
        $leave_type = $leave['leave_type'];
        if ($admin_role === 'principal' && $new_leave_type) {
            $leave_type = $new_leave_type;
            $sql_update_type = "UPDATE leave_applications SET leave_type = '$new_leave_type' WHERE id = $leave_id";
            $conn->query($sql_update_type);
        }

        // Approve leave
        $sql_approve = "UPDATE leave_applications 
                        SET status = 'approved', approved_by = $admin_id, approved_date = NOW() 
                        WHERE id = $leave_id";
        $conn->query($sql_approve);

        // Ensure leave_balance row exists (user_id, year)
        $sql_balance_check = "SELECT id FROM leave_balance 
                              WHERE user_id = {$leave['user_id']} AND year = {$leave['year']}";
        $bal_res = $conn->query($sql_balance_check);
        if ($bal_res->num_rows === 0) {
            $conn->query("INSERT INTO leave_balance (user_id, year) 
                          VALUES ({$leave['user_id']}, {$leave['year']})");
        }

        // Update leave balance
        // For leave_type 'casual','medical','duty' this becomes casual_leaves_used, etc.
        $field = $leave_type . '_leaves_used';
        $sql_balance = "UPDATE leave_balance 
                        SET $field = $field + {$leave['number_of_days']} 
                        WHERE user_id = {$leave['user_id']} AND year = {$leave['year']}";
        $conn->query($sql_balance);

        // Short leave tracking
        // IMPORTANT on DB: short_leave_tracking must have
        // UNIQUE KEY unique_user_month (user_id, year, month)
        if ($leave_type === 'short') {
            $sql_short = "INSERT INTO short_leave_tracking (user_id, year, month, short_leaves_count) 
                          VALUES ({$leave['user_id']}, {$leave['year']}, {$leave['month']}, 1)
                          ON DUPLICATE KEY UPDATE short_leaves_count = short_leaves_count + 1";

            if (!$conn->query($sql_short)) {
                error_log('SHORT LEAVE SQL ERROR: '.$conn->error.' | '.$sql_short);
            }
        }

        echo json_encode(['success' => true, 'message' => 'Leave approved successfully']);

    } elseif ($action === 'reject') {
        $sql_reject = "UPDATE leave_applications 
                       SET status = 'rejected', approved_by = $admin_id, approved_date = NOW() 
                       WHERE id = $leave_id";
        $conn->query($sql_reject);

        echo json_encode(['success' => true, 'message' => 'Leave rejected']);

    } elseif ($action === 'delete') {
        // Delete leave at any time (approved / pending / rejected)
        $sql_delete = "DELETE FROM leave_applications WHERE id = $leave_id";
        if ($conn->query($sql_delete)) {
            echo json_encode(['success' => true, 'message' => 'Leave deleted successfully']);
        } else {
            echo json_encode(['success' => false, 'message' => 'Error deleting leave: '.$conn->error]);
        }
    }

    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Approve Leaves - 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 active" 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 mt-4">
        <h2 class="mb-4">Approve Leave Applications</h2>

        <div class="alert alert-info">
            <i class="fas fa-info-circle"></i>
            <strong>Your Role: <?php echo ucfirst(str_replace('_', ' ', $admin_role)); ?></strong><br>
            <?php
            $limit = getApprovalLimit($admin_role);
            if ($limit === PHP_INT_MAX) {
                echo "You can approve leaves for employees with any number of annual leaves.";
            } else {
                echo "You can approve leaves for employees who have taken up to $limit leaves in a year.";
            }
            ?>
        </div>

        <div class="card">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="fas fa-list"></i> Pending Leave Applications</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table id="leavesTable" class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>Employee</th>
                                <th>Leave Type</th>
                                <th>Apply Date</th>
                                <th>Start Date</th>
                                <th>End Date</th>
                                <th>Days</th>
                                <th>Reason</th>
                                <th>Total Leaves</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Approval Modal -->
    <div class="modal fade" id="approvalModal" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Approve Leave</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="approve_leave_id">
                    <p id="approve_details"></p>

                    <?php if ($admin_role === 'principal'): ?>
                    <div class="mb-3">
                        <label class="form-label">Change Leave Type (Optional)</label>
                        <select class="form-select" id="new_leave_type">
                            <option value="">Keep Original</option>
                            <option value="casual">Casual Leave</option>
                            <option value="medical">Medical Leave</option>
                            <option value="duty">Duty Leave</option>
                            <option value="short">Short Leave</option>
                        </select>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-success" onclick="confirmApproval()">
                        <i class="fas fa-check"></i> Approve
                    </button>
                </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;
        const adminRole = '<?php echo $admin_role; ?>';

        $(document).ready(function() {
            loadPendingLeaves();
        });

        function loadPendingLeaves() {
            if (table) {
                table.destroy();
            }

            table = $('#leavesTable').DataTable({
                ajax: {
                    url: 'ajax_pending_leaves.php',
                    dataSrc: ''
                },
                columns: [
                    { data: 'employee_name' },
                    { data: 'leave_type' },
                    { data: 'apply_date' },
                    { data: 'start_date' },
                    { data: 'end_date' },
                    { data: 'number_of_days' },
                    { data: 'reason' },
                    { data: 'total_leaves' },
                    {
                        data: null,
                        render: function(data, type, row) {
                            let canApprove = <?php echo $admin_role === 'principal' ? 'true' : 'false'; ?>;
                            if (!canApprove) {
                                const limit = <?php echo getApprovalLimit($admin_role); ?>;
                                canApprove = parseFloat(row.total_leaves) <= limit;
                            }

                            let buttons = '';

                            if (canApprove) {
                                buttons += `
                                    <button class="btn btn-sm btn-success mb-1" onclick='approveLeave(${JSON.stringify(row)})'>
                                        <i class="fas fa-check"></i> Approve
                                    </button>
                                    <button class="btn btn-sm btn-danger mb-1" onclick="rejectLeave(${row.id})">
                                        <i class="fas fa-times"></i> Reject
                                    </button>
                                `;
                            } else {
                                buttons += '<span class="badge bg-warning mb-1 d-block">Requires Higher Authority</span>';
                            }

                            // Delete button (always available for admin)
                            buttons += `
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteLeave(${row.id})">
                                    <i class="fas fa-trash"></i> Delete
                                </button>
                            `;

                            return buttons;
                        }
                    }
                ],
                order: [[2, 'desc']]
            });
        }

        function approveLeave(data) {
            $('#approve_leave_id').val(data.id);
            $('#approve_details').html(`
                <strong>Employee:</strong> ${data.employee_name}<br>
                <strong>Leave Type:</strong> ${data.leave_type}<br>
                <strong>Apply Date:</strong> ${data.apply_date}<br>
                <strong>Duration:</strong> ${data.start_date} to ${data.end_date}<br>
                <strong>Days:</strong> ${data.number_of_days}<br>
                <strong>Reason:</strong> ${data.reason}
            `);
            $('#approvalModal').modal('show');
        }

        function confirmApproval() {
            const leaveId      = $('#approve_leave_id').val();
            const newLeaveType = $('#new_leave_type').length ? $('#new_leave_type').val() : '';

            $.post('approve_leaves.php', {
                leave_id: leaveId,
                action: 'approve',
                new_leave_type: newLeaveType
            }, function(response) {
                const data = JSON.parse(response);
                if (data.success) {
                    $('#approvalModal').modal('hide');
                    alert(data.message);
                    loadPendingLeaves();
                } else {
                    alert(data.message);
                }
            });
        }

        function rejectLeave(leaveId) {
            if (confirm('Are you sure you want to reject this leave application?')) {
                $.post('approve_leaves.php', {
                    leave_id: leaveId,
                    action: 'reject'
                }, function(response) {
                    const data = JSON.parse(response);
                    alert(data.message);
                    loadPendingLeaves();
                });
            }
        }

        function deleteLeave(leaveId) {
            if (confirm('Are you sure you want to delete this leave application? This cannot be undone.')) {
                $.post('approve_leaves.php', {
                    leave_id: leaveId,
                    action: 'delete'
                }, function(response) {
                    const data = JSON.parse(response);
                    alert(data.message);
                    loadPendingLeaves();
                });
            }
        }
    </script>
</body>
</html>
