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

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

$is_admin = isset($_SESSION['admin_id']);
$is_ac = isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'AC';

if (!$is_admin && !$is_ac) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

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

try {
    // Ensure overrides table exists (safe no-op if already exists)
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS yearly_points_overrides (
            record_year INT PRIMARY KEY,
            overall_total INT NOT NULL DEFAULT 0,
            updated_by_role VARCHAR(10) NULL,
            updated_by_admin_id INT NULL,
            updated_by_user_id INT NULL,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        )
    ");

    if ($action === 'update_overall_total') {
        $year = (int) ($_POST['year'] ?? 0);
        $overallTotal = (int) ($_POST['overall_total'] ?? 0);

        if ($year < 2000 || $year > 2100) {
            throw new Exception('Invalid year');
        }
        if ($overallTotal < 0) {
            throw new Exception('Overall total cannot be negative');
        }

        $updatedByRole = $is_admin ? 'ADMIN' : 'AC';
        $updatedByAdminId = $is_admin ? (int) $_SESSION['admin_id'] : null;
        $updatedByUserId = (!$is_admin && isset($_SESSION['user_id'])) ? (int) $_SESSION['user_id'] : null;

        $stmt = $pdo->prepare("
            INSERT INTO yearly_points_overrides (record_year, overall_total, updated_by_role, updated_by_admin_id, updated_by_user_id)
            VALUES (?, ?, ?, ?, ?)
            ON DUPLICATE KEY UPDATE
                overall_total = VALUES(overall_total),
                updated_by_role = VALUES(updated_by_role),
                updated_by_admin_id = VALUES(updated_by_admin_id),
                updated_by_user_id = VALUES(updated_by_user_id),
                updated_at = CURRENT_TIMESTAMP
        ");
        $stmt->execute([$year, $overallTotal, $updatedByRole, $updatedByAdminId, $updatedByUserId]);

        echo json_encode(['success' => true, 'message' => 'Saved']);
        exit;
    }

    throw new Exception('Invalid action');
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}


