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

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

if (!isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Invalid request method']);
    exit();
}

// Get event ID from POST request
$event_id = $_POST['event_id'] ?? '';

// Validate required field
if (empty($event_id)) {
    echo json_encode(['success' => false, 'message' => 'Event ID is required']);
    exit();
}

try {
    $conn = new PDO($dsn, $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Begin transaction
    $conn->beginTransaction();
    
    // Check if the event exists
    $stmt = $conn->prepare("SELECT title FROM events WHERE id = ?");
    $stmt->execute([$event_id]);
    $event = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$event) {
        $conn->rollBack();
        echo json_encode(['success' => false, 'message' => 'Event not found']);
        exit();
    }
    
    // Check if there are any related registrations
    $stmt = $conn->prepare("SELECT COUNT(*) FROM event_registrations WHERE event_id = ?");
    $stmt->execute([$event_id]);
    $registrationCount = $stmt->fetchColumn();
    
    if ($registrationCount > 0) {
        // Update event status to 'cancelled' instead of deleting
        $stmt = $conn->prepare("UPDATE events SET status = 'cancelled', updated_at = CURRENT_TIMESTAMP WHERE id = ?");
        $stmt->execute([$event_id]);
        
        // Log the action
        $stmt = $conn->prepare("
            INSERT INTO admin_logs (admin_id, action, details, created_at)
            VALUES (?, 'cancel_event', ?, CURRENT_TIMESTAMP)
        ");
        $stmt->execute([
            $_SESSION['admin_id'],
            'Cancelled event: ' . $event['title'] . ' (ID: ' . $event_id . ') due to existing registrations'
        ]);
        
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Event cancelled successfully (not deleted due to existing registrations)',
            'cancelled' => true
        ]);
    } else {
        // Delete the event from the database
        $stmt = $conn->prepare("DELETE FROM events WHERE id = ?");
        $stmt->execute([$event_id]);
        
        // Log the action
        $stmt = $conn->prepare("
            INSERT INTO admin_logs (admin_id, action, details, created_at)
            VALUES (?, 'delete_event', ?, CURRENT_TIMESTAMP)
        ");
        $stmt->execute([
            $_SESSION['admin_id'],
            'Deleted event: ' . $event['title'] . ' (ID: ' . $event_id . ')'
        ]);
        
        $conn->commit();
        
        echo json_encode([
            'success' => true,
            'message' => 'Event deleted successfully',
            'deleted' => true
        ]);
    }
    
} catch (PDOException $e) {
    if ($conn) {
        $conn->rollBack();
    }
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
