<?php
require_once 'init.php';

// Suraksha jaanch
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];

// Form submission handle karna
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $leave_type = $_POST['leave_type'];
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $reason = $_POST['reason'];

    // Validation
    if (empty($leave_type) || empty($start_date) || empty($end_date) || empty($reason)) {
        $_SESSION['message'] = "All fields are required.";
        $_SESSION['message_type'] = 'error';
    } elseif (new DateTime($start_date) > new DateTime($end_date)) {
        $_SESSION['message'] = "End date cannot be before the start date.";
        $_SESSION['message_type'] = 'error';
    } else {
        // Database mein insert karein
        $stmt = $conn->prepare("INSERT INTO leave_requests (user_id, leave_type, start_date, end_date, reason) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("issss", $user_id, $leave_type, $start_date, $end_date, $reason);

        if ($stmt->execute()) {
            $_SESSION['message'] = "Leave request submitted successfully.";
            $_SESSION['message_type'] = 'success';
        } else {
            $_SESSION['message'] = "Error submitting request: " . $stmt->error;
            $_SESSION['message_type'] = 'error';
        }
        $stmt->close();
    }
    // Redirect to the same page to show the message and prevent form resubmission
    header("Location: leave-request.php");
    exit();
}

// User ke purane leave requests fetch karna
$leave_requests = []; // Default to empty array
// FIX: Changed ORDER BY from 'created_at' to 'id' to prevent unknown column error.
$stmt = $conn->prepare("SELECT * FROM leave_requests WHERE user_id = ? ORDER BY id DESC");

if ($stmt) {
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $leave_requests_result = $stmt->get_result();
    $leave_requests = $leave_requests_result->fetch_all(MYSQLI_ASSOC);
    $stmt->close();
} else {
    // Reverted to a user-friendly error message now that the issue is known.
    $_SESSION['message'] = "Could not retrieve leave history due to a database error.";
    $_SESSION['message_type'] = 'error';
}


// Session se message prapt karein
$message = $_SESSION['message'] ?? '';
$message_type = $_SESSION['message_type'] ?? '';
unset($_SESSION['message'], $_SESSION['message_type']);

require_once 'header.php';
?>

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

<div class="flex-1" x-data="{}">
    <header class="bg-white shadow-sm p-4">
        <h2 class="text-xl font-bold text-gray-800">Leave Request</h2>
    </header>

    <main class="p-6 md:p-10">
        <?php if ($message): ?>
            <div class="mb-6 p-4 rounded-lg <?php echo ($message_type == 'success') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- New Leave Request Form -->
            <div class="lg:col-span-1 bg-white p-6 rounded-lg shadow-md">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">Submit a New Request</h3>
                <form method="POST" action="leave-request.php">
                    <div class="space-y-4">
                        <div>
                            <label for="leave_type" class="block text-sm font-medium text-gray-700">Leave Type</label>
                            <select id="leave_type" name="leave_type" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500">
                                <option value="">Select type...</option>
                                <option value="Paid Leave">Paid Leave</option>
                                <option value="Sick Leave">Sick Leave</option>
                                <option value="Unpaid Leave">Unpaid Leave</option>
                                <option value="Other">Other</option>
                            </select>
                        </div>
                        <div>
                            <label for="start_date" class="block text-sm font-medium text-gray-700">Start Date</label>
                            <input type="date" id="start_date" name="start_date" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label for="end_date" class="block text-sm font-medium text-gray-700">End Date</label>
                            <input type="date" id="end_date" name="end_date" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500">
                        </div>
                        <div>
                            <label for="reason" class="block text-sm font-medium text-gray-700">Reason for Leave</label>
                            <textarea id="reason" name="reason" rows="4" required class="mt-1 block w-full border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500"></textarea>
                        </div>
                    </div>
                    <div class="mt-6">
                        <button type="submit" class="w-full bg-blue-600 text-white font-semibold py-2 px-4 rounded-lg shadow-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                            Submit Request
                        </button>
                    </div>
                </form>
            </div>

            <!-- Leave History Table -->
            <div class="lg:col-span-2 bg-white p-6 rounded-lg shadow-md">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">Your Leave History</h3>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Type</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Dates</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Reason</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200">
                            <?php if (empty($leave_requests)): ?>
                                <tr>
                                    <td colspan="4" class="px-6 py-4 whitespace-nowrap text-sm text-gray-500 text-center">You have no leave requests.</td>
                                </tr>
                            <?php else: ?>
                                <?php foreach ($leave_requests as $request): ?>
                                    <tr>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm font-medium text-gray-900"><?php echo htmlspecialchars($request['leave_type']); ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                                            <?php echo date('d M, Y', strtotime($request['start_date'])); ?> - <?php echo date('d M, Y', strtotime($request['end_date'])); ?>
                                        </td>
                                        <td class="px-6 py-4 whitespace-normal text-sm text-gray-500 max-w-xs break-words"><?php echo htmlspecialchars($request['reason']); ?></td>
                                        <td class="px-6 py-4 whitespace-nowrap text-sm">
                                            <span class="px-2 inline-flex text-xs leading-5 font-semibold rounded-full 
                                                <?php 
                                                    if ($request['status'] == 'Approved') echo 'bg-green-100 text-green-800';
                                                    elseif ($request['status'] == 'Rejected') echo 'bg-red-100 text-red-800';
                                                    else echo 'bg-yellow-100 text-yellow-800';
                                                ?>">
                                                <?php echo htmlspecialchars($request['status']); ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </main>
</div>

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

