<?php
require_once __DIR__ . '/../../config/config.php';
header('Content-Type: application/json');

try {
    $announcement_id = (int)($_POST['announcement_id'] ?? 0);
    $course_id = (int)($_POST['course_id'] ?? 0);
    $academic_year = trim($_POST['academic_year'] ?? '');
    $exam_type_id = (int)($_POST['exam_type_id'] ?? 0);
    $start_at = trim($_POST['start_at'] ?? '');
    $end_at = trim($_POST['end_at'] ?? '');
    $is_active = isset($_POST['is_active']) ? (int)$_POST['is_active'] : 1;

    if($announcement_id <= 0 || $course_id <= 0 || !$academic_year || $exam_type_id <= 0 || !$start_at || !$end_at){
        echo json_encode(['status' => 'error', 'message' => 'Missing required fields']); 
        exit;
    }
    
    global $pdo;
    
    // Check if table exists
    $stmt = $pdo->query("SHOW TABLES LIKE 'result_announcements'");
    if ($stmt->rowCount() == 0) {
        echo json_encode(['status' => 'error', 'message' => 'Table not found']);
        exit;
    }
    
    // Check for duplicates (excluding current record)
    $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM result_announcements 
                          WHERE course_id = ? AND academic_year = ? AND exam_type_id = ? 
                          AND announcement_id != ?");
    $stmt->execute([$course_id, $academic_year, $exam_type_id, $announcement_id]);
    $duplicate = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if ($duplicate['count'] > 0) {
        echo json_encode(['status' => 'error', 'message' => 'Announcement already exists for this course, academic year, and exam type']);
        exit;
    }
    
    // Update the record
    $stmt = $pdo->prepare("UPDATE result_announcements 
                          SET course_id = ?, academic_year = ?, exam_type_id = ?, 
                              start_at = ?, end_at = ?, is_active = ?, updated_at = CURRENT_TIMESTAMP
                          WHERE announcement_id = ?");
    $stmt->execute([$course_id, $academic_year, $exam_type_id, $start_at, $end_at, $is_active, $announcement_id]);
    
    if ($stmt->rowCount() > 0) {
        echo json_encode(['status' => 'success', 'message' => 'Announcement updated successfully']);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No changes made or record not found']);
    }
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>
