<?php
session_start();
include 'config.php';

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Debugging: Log session data
error_log("Submit Leave - Session Data: " . print_r($_SESSION, true), 3, "debug.log");

// Check if user is logged in
if (!isset($_SESSION['user_id']) || empty($_SESSION['user_id'])) {
    error_log("Submit Leave - No user_id in session, redirecting to index.php", 3, "debug.log");
    $_SESSION['error'] = "Please log in to continue.";
    header("Location: index.php");
    exit();
}

// Verify user exists
$user_sql = "SELECT id FROM users WHERE id = ?";
$stmt = $conn->prepare($user_sql);
if (!$stmt) {
    error_log("Submit Leave - User query preparation failed: " . $conn->error, 3, "debug.log");
    $_SESSION['error'] = "Database error. Please try again.";
    header("Location: leave_dashboard.php");
    exit();
}
$stmt->bind_param("s", $_SESSION['user_id']);
if (!$stmt->execute()) {
    error_log("Submit Leave - User query execution failed: " . $stmt->error, 3, "debug.log");
    $_SESSION['error'] = "Database error. Please try again.";
    header("Location: leave_dashboard.php");
    exit();
}
$user_result = $stmt->get_result();
if ($user_result->num_rows === 0) {
    error_log("Submit Leave - No user found for user_id: " . $_SESSION['user_id'], 3, "debug.log");
    $_SESSION['error'] = "User not found.";
    header("Location: index.php");
    exit();
}
$user = $user_result->fetch_assoc();
$employee_id = $user['id'];
$stmt->close();

// Validate form submission
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    error_log("Submit Leave - Invalid request method", 3, "debug.log");
    $_SESSION['error'] = "Invalid request.";
    header("Location: leave_dashboard.php");
    exit();
}

// Validate input
$leave_type = trim($_POST['leave_type'] ?? '');
$start_date = trim($_POST['start_date'] ?? '');
$end_date = trim($_POST['end_date'] ?? '');
$reason = trim($_POST['reason'] ?? '');

$valid_leave_types = ['CL', 'PL', 'SL', 'Compensatory', 'Custom'];
if (!in_array($leave_type, $valid_leave_types)) {
    error_log("Submit Leave - Invalid leave_type: $leave_type", 3, "debug.log");
    $_SESSION['error'] = "Invalid leave type.";
    header("Location: leave_dashboard.php");
    exit();
}

if (!$start_date || !$end_date || !strtotime($start_date) || !strtotime($end_date)) {
    error_log("Submit Leave - Invalid dates: start_date=$start_date, end_date=$end_date", 3, "debug.log");
    $_SESSION['error'] = "Invalid start or end date.";
    header("Location: leave_dashboard.php");
    exit();
}

if (strtotime($end_date) < strtotime($start_date)) {
    error_log("Submit Leave - End date before start date: start_date=$start_date, end_date=$end_date", 3, "debug.log");
    $_SESSION['error'] = "End date cannot be before start date.";
    header("Location: leave_dashboard.php");
    exit();
}

if (empty($reason)) {
    error_log("Submit Leave - Empty reason", 3, "debug.log");
    $_SESSION['error'] = "Please provide a reason for the leave.";
    header("Location: leave_dashboard.php");
    exit();
}

// Insert leave request
$insert_sql = "INSERT INTO leave_requests (employee_id, leave_type, start_date, end_date, reason, status) VALUES (?, ?, ?, ?, ?, 'Pending')";
$stmt = $conn->prepare($insert_sql);
if (!$stmt) {
    error_log("Submit Leave - Insert query preparation failed: " . $conn->error, 3, "debug.log");
    $_SESSION['error'] = "Database error. Please try again.";
    header("Location: leave_dashboard.php");
    exit();
}
$stmt->bind_param("sssss", $employee_id, $leave_type, $start_date, $end_date, $reason);
if (!$stmt->execute()) {
    error_log("Submit Leave - Insert query execution failed: " . $stmt->error, 3, "debug.log");
    $_SESSION['error'] = "Failed to submit leave request.";
    header("Location: leave_dashboard.php");
    exit();
}
$stmt->close();

$_SESSION['message'] = "Leave request submitted successfully.";
error_log("Submit Leave - Leave request submitted for employee_id: $employee_id, leave_type: $leave_type", 3, "debug.log");
header("Location: leave_dashboard.php");
exit();
?>