<?php
header('Content-Type: application/json');
require_once("../../includes/config.php");
session_start();

// 1. Basic Security Check
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized access']);
    exit;
}

$action = $_GET['action'] ?? '';

try {
    // --- DELETE ACTION ---
    if ($action === 'delete') {
        $id = $_POST['id'] ?? 0;

        if (!$id) throw new Exception("Invalid ID provided.");

        // Check if marks are already linked to this term before deleting
        $check = $pdo->prepare("SELECT COUNT(*) FROM marks_entry WHERE exam_term_id = ?");
        $check->execute([$id]);
        if ($check->fetchColumn() > 0) {
            throw new Exception("Cannot delete: Marks have already been recorded for this term.");
        }

        $stmt = $pdo->prepare("DELETE FROM exam_terms WHERE id = ?");
        $stmt->execute([$id]);

        echo json_encode(['status' => 'success', 'message' => 'Exam term deleted successfully']);
    }

    // --- UPDATE ACTION ---
    elseif ($action === 'update') {
        $id = $_POST['id'] ?? 0;
        $name = trim($_POST['term_name'] ?? '');
        $marks = trim($_POST['max_marks'] ?? '');

        $status = $_POST['status'] ?? 1;

        if (empty($name)) throw new Exception("Exam term name is required.");
        if (!$id) throw new Exception("ID is missing.");

        $stmt = $pdo->prepare("UPDATE exam_terms SET term_name = ?, max_marks = ?, status = ? WHERE id = ?");
        $stmt->execute([$name, $marks, $status, $id]);

        echo json_encode(['status' => 'success', 'message' => 'Exam term updated successfully']);
    }

    else {
        throw new Exception("Invalid action specified.");
    }

} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}?>