<?php
require_once '../../config/config.php';

header('Content-Type: application/json');

function respond($ok, $msg, $extra = []) {
    echo json_encode(($ok ? ['status' => 'success'] : ['status' => 'error']) + ['message' => $msg] + $extra);
    exit;
}

try {
    $method = $_SERVER['REQUEST_METHOD'];
    
    switch ($method) {
        case 'GET':
            handleRead();
            break;
        case 'POST':
            handleCreate();
            break;
        case 'PUT':
            handleUpdate();
            break;
        case 'DELETE':
            handleDelete();
            break;
        default:
            respond(false, 'Method not allowed');
    }
} catch (Exception $e) {
    respond(false, $e->getMessage());
}

function handleRead() {
    global $pdo;
    
    $hallId = $_GET['hall_id'] ?? '';
    $examDate = $_GET['exam_date'] ?? '';
    $session = $_GET['session'] ?? '';
    $staffId = $_GET['staff_id'] ?? '';
    $role = $_GET['role'] ?? '';
    $status = $_GET['status'] ?? '';
    $allocationId = $_GET['allocation_id'] ?? '';
    
    $where = [];
    $params = [];
    
    if ($hallId) {
        $where[] = "id.hall_id = ?";
        $params[] = $hallId;
    }
    if ($examDate) {
        $where[] = "id.exam_date = ?";
        $params[] = $examDate;
    }
    if ($session) {
        $where[] = "id.session = ?";
        $params[] = $session;
    }
    if ($staffId) {
        $where[] = "id.staff_id = ?";
        $params[] = $staffId;
    }
    if ($role) {
        $where[] = "id.role = ?";
        $params[] = $role;
    }
    if ($status) {
        $where[] = "id.status = ?";
        $params[] = $status;
    }
    if ($allocationId) {
        $where[] = "id.allocation_id = ?";
        $params[] = $allocationId;
    }
    
    $whereClause = $where ? 'WHERE ' . implode(' AND ', $where) : '';
    
    $sql = "
        SELECT id.*, 
               h.hall_name,
               s.first_name, s.last_name, s.staff_code,
               ha.num_students,
               et.exam_date, et.session as exam_session
        FROM invigilation_duties id
        LEFT JOIN halls h ON id.hall_id = h.hall_id
        LEFT JOIN staff s ON id.staff_id = s.staff_id
        LEFT JOIN hall_allocations ha ON id.allocation_id = ha.allocation_id
        LEFT JOIN exam_timetable et ON ha.timetable_id = et.timetable_id
        $whereClause
        ORDER BY id.exam_date DESC, id.session, h.hall_name, id.role
    ";
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);
    $data = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    respond(true, 'Data retrieved successfully', ['data' => $data]);
}

function handleCreate() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    
    $hallId = $input['hall_id'] ?? '';
    $examDate = $input['exam_date'] ?? '';
    $session = $input['session'] ?? '';
    $staffId = $input['staff_id'] ?? '';
    $role = $input['role'] ?? '';
    $allocationId = $input['allocation_id'] ?? null;
    $status = $input['status'] ?? 'Assigned';
    
    if (!$hallId || !$examDate || !$session || !$staffId || !$role) {
        respond(false, 'Missing required fields');
    }
    
    // Check if staff already assigned to this hall on this date/session
    $checkStmt = $pdo->prepare("
        SELECT duty_id FROM invigilation_duties 
        WHERE hall_id = ? AND exam_date = ? AND session = ? AND staff_id = ?
    ");
    $checkStmt->execute([$hallId, $examDate, $session, $staffId]);
    if ($checkStmt->fetch()) {
        respond(false, 'Staff already assigned to this hall on this date/session');
    }
    
    $sql = "
        INSERT INTO invigilation_duties 
        (hall_id, exam_date, session, staff_id, role, allocation_id, status) 
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ";
    
    $stmt = $pdo->prepare($sql);
    $result = $stmt->execute([$hallId, $examDate, $session, $staffId, $role, $allocationId, $status]);
    
    if ($result) {
        respond(true, 'Invigilation duty created successfully', ['duty_id' => $pdo->lastInsertId()]);
    } else {
        respond(false, 'Failed to create invigilation duty');
    }
}

function handleUpdate() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $dutyId = $input['duty_id'] ?? '';
    
    if (!$dutyId) {
        respond(false, 'Duty ID is required');
    }
    
    $fields = [];
    $params = [];
    
    $allowedFields = ['hall_id', 'exam_date', 'session', 'staff_id', 'role', 'allocation_id', 'status'];
    
    foreach ($allowedFields as $field) {
        if (isset($input[$field])) {
            $fields[] = "$field = ?";
            $params[] = $input[$field];
        }
    }
    
    if (empty($fields)) {
        respond(false, 'No fields to update');
    }
    
    $params[] = $dutyId;
    
    $sql = "UPDATE invigilation_duties SET " . implode(', ', $fields) . " WHERE duty_id = ?";
    $stmt = $pdo->prepare($sql);
    $result = $stmt->execute($params);
    
    if ($result) {
        respond(true, 'Invigilation duty updated successfully');
    } else {
        respond(false, 'Failed to update invigilation duty');
    }
}

function handleDelete() {
    global $pdo;
    
    $input = json_decode(file_get_contents('php://input'), true);
    $dutyId = $input['duty_id'] ?? '';
    
    if (!$dutyId) {
        respond(false, 'Duty ID is required');
    }
    
    $stmt = $pdo->prepare("DELETE FROM invigilation_duties WHERE duty_id = ?");
    $result = $stmt->execute([$dutyId]);
    
    if ($result) {
        respond(true, 'Invigilation duty deleted successfully');
    } else {
        respond(false, 'Failed to delete invigilation duty');
    }
}
?>
