<?php
require_once 'init.php';

// Suraksha jaanch: Sirf Admin ya Manager hi is page ko access kar sakte hain.
if (!userHasRole(['Admin', 'Manager'])) {
    echo "<div class='p-6'>Access Denied. You do not have the required permissions to view this page.</div>";
    exit();
}

// --- ACTION LOGIC (APPROVE/REJECT) ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action'])) {
    $leave_id = $_POST['leave_id'];
    $action = $_POST['action']; // 'Approved' ya 'Rejected'

    if ($action === 'Approved' || $action === 'Rejected') {
        $stmt = $conn->prepare("UPDATE leave_requests SET status = ? WHERE id = ?");
        $stmt->bind_param("si", $action, $leave_id);
        if ($stmt->execute()) {
            $_SESSION['message'] = "Leave request has been " . strtolower($action) . ".";
            $_SESSION['message_type'] = 'success';
        } else {
            $_SESSION['message'] = "Error updating leave request.";
            $_SESSION['message_type'] = 'error';
        }
        $stmt->close();
    }
    // Form resubmission se bachne ke liye redirect karein
    header("Location: leave-management.php");
    exit();
}

// --- FILTER LOGIC ---
$user_filter = $_GET['user_id'] ?? 'all';
$start_date_filter = $_GET['start_date'] ?? '';
$end_date_filter = $_GET['end_date'] ?? '';

// --- DATA FETCHING ---

// Sabhi employees ko filter ke liye prapt karein
$employees_result = $conn->query("SELECT id, name FROM users ORDER BY name ASC");
$employees = $employees_result->fetch_all(MYSQLI_ASSOC);

// Pending leave requests prapt karein
$pending_requests_sql = "SELECT lr.*, u.name as user_name FROM leave_requests lr JOIN users u ON lr.user_id = u.id WHERE lr.status = 'Pending' ORDER BY lr.start_date ASC";
$pending_requests_result = $conn->query($pending_requests_sql);
$pending_requests = $pending_requests_result->fetch_all(MYSQLI_ASSOC);

// Leave history prapt karein (filters ke saath)
$history_params = [];
$history_param_types = '';
$history_sql = "SELECT lr.*, u.name as user_name FROM leave_requests lr JOIN users u ON lr.user_id = u.id WHERE lr.status != 'Pending'";

if ($user_filter !== 'all' && is_numeric($user_filter)) {
    $history_sql .= " AND lr.user_id = ?";
    $history_params[] = $user_filter;
    $history_param_types .= 'i';
}
if (!empty($start_date_filter)) {
    // Aisi leaves dhoondhein jinka end date filter ke start date ke baad ho
    $history_sql .= " AND lr.end_date >= ?";
    $history_params[] = $start_date_filter;
    $history_param_types .= 's';
}
if (!empty($end_date_filter)) {
    // Aisi leaves dhoondhein jinka start date filter ke end date se pehle ho
    $history_sql .= " AND lr.start_date <= ?";
    $history_params[] = $end_date_filter;
    $history_param_types .= 's';
}
$history_sql .= " ORDER BY lr.start_date DESC";

$stmt_history = $conn->prepare($history_sql);
if (!empty($history_params)) {
    $stmt_history->bind_param($history_param_types, ...$history_params);
}
$stmt_history->execute();
$history_result = $stmt_history->get_result();
$leave_history = $history_result->fetch_all(MYSQLI_ASSOC);


require_once 'header.php';
?>

<title>Leave Management - Digify OS</title>

<div class="p-6 md:p-10">
    <header class="mb-8">
        <h2 class="text-2xl font-bold text-gray-800">Leave Management Dashboard</h2>
        <p class="text-gray-600">Review pending leave requests and browse team's leave history.</p>
    </header>

    <?php if (isset($_SESSION['message'])): ?>
    <div class="mb-6 p-4 rounded-lg <?php echo ($_SESSION['message_type'] == 'success') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
        <?php echo htmlspecialchars($_SESSION['message']); unset($_SESSION['message'], $_SESSION['message_type']); ?>
    </div>
    <?php endif; ?>

    <!-- Pending Leave Requests Section -->
    <div class="bg-white p-6 rounded-lg shadow-md mb-8">
        <h3 class="text-xl font-semibold text-gray-700 mb-4 border-b pb-2">Pending Leave Requests</h3>
        <div class="overflow-x-auto">
            <table class="min-w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Employee</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Dates</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Reason</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Actions</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($pending_requests)): ?>
                        <tr><td colspan="4" class="px-6 py-10 text-center text-gray-500">No pending leave requests.</td></tr>
                    <?php else: ?>
                        <?php foreach ($pending_requests as $request): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo htmlspecialchars($request['user_name']); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700"><?php echo date("d M, Y", strtotime($request['start_date'])); ?> to <?php echo date("d M, Y", strtotime($request['end_date'])); ?></td>
                                <td class="px-6 py-4 text-sm text-gray-600 max-w-xs truncate"><?php echo htmlspecialchars($request['reason']); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                                    <form method="POST" action="leave-management.php" class="inline">
                                        <input type="hidden" name="leave_id" value="<?php echo $request['id']; ?>">
                                        <button type="submit" name="action" value="Approved" class="px-3 py-1 bg-green-500 text-white rounded-md text-xs hover:bg-green-600">Approve</button>
                                    </form>
                                    <form method="POST" action="leave-management.php" class="inline ml-2">
                                        <input type="hidden" name="leave_id" value="<?php echo $request['id']; ?>">
                                        <button type="submit" name="action" value="Rejected" class="px-3 py-1 bg-red-500 text-white rounded-md text-xs hover:bg-red-600">Reject</button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Leave History Section -->
    <div class="bg-white p-6 rounded-lg shadow-md">
        <h3 class="text-xl font-semibold text-gray-700 mb-4 border-b pb-2">Leave History</h3>
        <!-- Filters -->
        <form method="GET" action="leave-management.php" class="mb-6 bg-gray-50 p-4 rounded-md">
            <div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
                <div>
                    <label for="user_id" class="text-sm font-medium text-gray-700">Employee</label>
                    <select name="user_id" id="user_id" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                        <option value="all">All Employees</option>
                        <?php foreach ($employees as $employee): ?>
                            <option value="<?php echo $employee['id']; ?>" <?php if ($user_filter == $employee['id']) echo 'selected'; ?>>
                                <?php echo htmlspecialchars($employee['name']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label for="start_date" class="text-sm font-medium text-gray-700">From Date</label>
                    <input type="date" name="start_date" id="start_date" value="<?php echo htmlspecialchars($start_date_filter); ?>" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                </div>
                 <div>
                    <label for="end_date" class="text-sm font-medium text-gray-700">To Date</label>
                    <input type="date" name="end_date" id="end_date" value="<?php echo htmlspecialchars($end_date_filter); ?>" class="mt-1 w-full border-gray-300 rounded-md shadow-sm">
                </div>
                <div class="flex items-center space-x-2">
                    <button type="submit" class="px-6 py-2 bg-blue-600 text-white font-semibold rounded-lg shadow-md hover:bg-blue-700">Filter</button>
                    <a href="leave-management.php" class="px-4 py-2 text-sm text-gray-600 hover:underline">Reset</a>
                </div>
            </div>
        </form>

        <div class="overflow-x-auto">
             <table class="min-w-full">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Employee</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Dates</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Reason</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Status</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    <?php if (empty($leave_history)): ?>
                        <tr><td colspan="4" class="px-6 py-10 text-center text-gray-500">No leave history found for the selected criteria.</td></tr>
                    <?php else: ?>
                        <?php foreach ($leave_history as $record): ?>
                            <tr>
                                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo htmlspecialchars($record['user_name']); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-700"><?php echo date("d M, Y", strtotime($record['start_date'])); ?> to <?php echo date("d M, Y", strtotime($record['end_date'])); ?></td>
                                <td class="px-6 py-4 text-sm text-gray-600 max-w-xs truncate"><?php echo htmlspecialchars($record['reason']); ?></td>
                                <td class="px-6 py-4 whitespace-nowrap text-sm">
                                    <?php
                                        $status = htmlspecialchars($record['status']);
                                        $status_color = ($status == 'Approved') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800';
                                    ?>
                                    <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full <?php echo $status_color; ?>">
                                        <?php echo $status; ?>
                                    </span>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<?php
require_once 'footer.php';
?>
