<?php
session_start();
require_once '../config/database.php';

// Set JSON header
header('Content-Type: application/json; charset=UTF-8');

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || !in_array($_SESSION['user_role'], ['admin', 'teacher'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit();
}

$id = $_POST['id'] ?? '';
$exam_date = $_POST['exam_date'] ?? '';
$start_time = $_POST['start_time'] ?? '';
$end_time = $_POST['end_time'] ?? '';
$marks = $_POST['marks'] ?? '';
$room_number = $_POST['room_number'] ?? '';
$invigilator = $_POST['invigilator'] ?? '';

if (!$id) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Subject ID required']);
    exit();
}

try {
    $stmt = $pdo->prepare("
        UPDATE exam_subjects 
        SET exam_date = ?, start_time = ?, end_time = ?, marks = ?, room_number = ?, invigilator = ?
        WHERE id = ?
    ");
    $result = $stmt->execute([$exam_date, $start_time, $end_time, $marks, $room_number, $invigilator, $id]);
    
    // Check if any rows were affected
    if ($stmt->rowCount() > 0) {
        echo json_encode(['success' => true, 'message' => 'Subject updated successfully']);
    } else {
        // Still treat as success since no changes might have been needed
        echo json_encode(['success' => true, 'message' => 'No changes were needed']);
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
?>