<?php
session_start();
require_once '../../admin/includes/database.php';
require_once '../../admin/Classes/Attendance.php';

header('Content-Type: application/json');

$conn = new Database();

if (!isset($_SESSION['student'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}


// Validate required fields
$required = ['student_id', 'leave_type', 'start_date', 'end_date', 'reason'];
foreach($required as $field) {
    if(!isset($_POST[$field]) || empty(trim($_POST[$field]))) {
        echo json_encode(['success' => false, 'message' => 'All fields are required']);
        exit();
    }
}

$studentId = $_POST['student_id'];
$leaveType = trim($_POST['leave_type']);
$startDate = $_POST['start_date'];
$endDate = $_POST['end_date'];
$reason = trim($_POST['reason']);

// Verify student ownership
$sql = "SELECT studentID, name FROM student WHERE studentID = :student_id AND username = :username";
$conn->query($sql);
$conn->bind(':student_id', $studentId);
$conn->bind(':username', $_SESSION['student']);
$student = $conn->fetchSingle();

if(!$student) {
    echo json_encode(['success' => false, 'message' => 'Invalid student']);
    exit();
}

// Validate dates
$start = new DateTime($startDate);
$end = new DateTime($endDate);
$today = new DateTime();
$today->setTime(0, 0, 0);

if($start < $today) {
    echo json_encode(['success' => false, 'message' => 'Start date cannot be in the past']);
    exit();
}

if($end < $start) {
    echo json_encode(['success' => false, 'message' => 'End date must be after start date']);
    exit();
}

// Check for overlapping leave requests
$sql = "SELECT id FROM attendance_leave_requests 
        WHERE student_id = :student_id 
        AND status = 'pending'
        AND (
            (leave_from <= :end_date AND leave_to >= :start_date)
        )";
$conn->query($sql);
$conn->bind(':student_id', $studentId);
$conn->bind(':start_date', $startDate);
$conn->bind(':end_date', $endDate);
$existing = $conn->fetchSingle();

if($existing) {
    echo json_encode(['success' => false, 'message' => 'You already have a pending leave request for these dates']);
    exit();
}

// Insert leave request
try {
    $sql = "INSERT INTO attendance_leave_requests 
            (student_id, leave_type, leave_from, leave_to, reason, status, requested_at)
            VALUES 
            (:student_id, :leave_type, :start_date, :end_date, :reason, 'pending', NOW())";

    $conn->query($sql);
    $conn->bind(':student_id', $studentId);
    $conn->bind(':leave_type', $leaveType);
    $conn->bind(':start_date', $startDate);
    $conn->bind(':end_date', $endDate);
    $conn->bind(':reason', $reason);

    if($conn->execute()) {
        // Create notification for admin
        $sql = "INSERT INTO attendance_notifications 
                (student_id, notification_type, message, is_read, sent_at)
                VALUES 
                (:student_id, 'leave_request', :message, 0, NOW())";
        $conn->query($sql);
        $conn->bind(':student_id', $studentId);
        $message = $student->name . ' has submitted a leave request from ' . $startDate . ' to ' . $endDate;
        $conn->bind(':message', $message);
        $conn->execute();

        echo json_encode([
            'success' => true,
            'message' => 'Leave request submitted successfully'
        ]);
    } else {
        echo json_encode([
            'success' => false,
            'message' => 'Failed to submit leave request'
        ]);
    }
} catch(Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
