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

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

// Check if user is logged in and has permission
if (!isset($_SESSION['user_id']) || !has_permission('events_manage')) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Yetkisiz erişim']);
    exit();
}

$method = $_SERVER['REQUEST_METHOD'];

try {
    switch ($method) {
        case 'POST':
            // Add new seasonal event
            $event_name = $_POST['event_name'] ?? '';
            $event_type = $_POST['event_type'] ?? '';
            $start_date = $_POST['start_date'] ?? '';
            $end_date = $_POST['end_date'] ?? '';
            $bonus_amount = $_POST['bonus_amount'] ?? 0;
            $status = $_POST['status'] ?? 'active';
            $description = $_POST['description'] ?? '';

            if (empty($event_name) || empty($event_type) || empty($start_date) || empty($end_date)) {
                throw new Exception('Gerekli alanlar eksik');
            }

            $stmt = $pdo->prepare("INSERT INTO seasonal_events (event_name, event_type, start_date, end_date, bonus_amount, status, description, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([$event_name, $event_type, $start_date, $end_date, $bonus_amount, $status, $description]);

            // Log the action
            log_admin_action($_SESSION['user_id'], 'seasonal_event_add', "Added seasonal event: $event_name");

            echo json_encode(['success' => true, 'message' => 'Etkinlik başarıyla eklendi']);
            break;

        case 'PUT':
            // Update seasonal event
            $input = json_decode(file_get_contents('php://input'), true);
            $id = $input['id'] ?? 0;
            $event_name = $input['event_name'] ?? '';
            $event_type = $input['event_type'] ?? '';
            $start_date = $input['start_date'] ?? '';
            $end_date = $input['end_date'] ?? '';
            $bonus_amount = $input['bonus_amount'] ?? 0;
            $status = $input['status'] ?? 'active';
            $description = $input['description'] ?? '';

            if (!$id || empty($event_name)) {
                throw new Exception('Geçersiz veri');
            }

            $stmt = $pdo->prepare("UPDATE seasonal_events SET event_name = ?, event_type = ?, start_date = ?, end_date = ?, bonus_amount = ?, status = ?, description = ? WHERE id = ?");
            $stmt->execute([$event_name, $event_type, $start_date, $end_date, $bonus_amount, $status, $description, $id]);

            // Log the action
            log_admin_action($_SESSION['user_id'], 'seasonal_event_update', "Updated seasonal event ID: $id");

            echo json_encode(['success' => true, 'message' => 'Etkinlik başarıyla güncellendi']);
            break;

        case 'DELETE':
            // Delete seasonal event
            $input = json_decode(file_get_contents('php://input'), true);
            $id = $input['id'] ?? 0;

            if (!$id) {
                throw new Exception('Geçersiz ID');
            }

            // Check if event has participants
            $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM tournament_participants tp JOIN tournaments t ON tp.tournament_id = t.id WHERE t.event_id = ?");
            $stmt->execute([$id]);
            $participants = $stmt->fetch()['count'];

            if ($participants > 0) {
                throw new Exception('Bu etkinliğe katılımcılar var, silinemez');
            }

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

            // Log the action
            log_admin_action($_SESSION['user_id'], 'seasonal_event_delete', "Deleted seasonal event ID: $id");

            echo json_encode(['success' => true, 'message' => 'Etkinlik başarıyla silindi']);
            break;

        case 'GET':
            // Get seasonal event details
            $id = $_GET['id'] ?? 0;

            if (!$id) {
                throw new Exception('Geçersiz ID');
            }

            $stmt = $pdo->prepare("SELECT * FROM seasonal_events WHERE id = ?");
            $stmt->execute([$id]);
            $event = $stmt->fetch();

            if (!$event) {
                throw new Exception('Etkinlik bulunamadı');
            }

            echo json_encode(['success' => true, 'data' => $event]);
            break;

        default:
            throw new Exception('Geçersiz HTTP metodu');
    }

} catch (Exception $e) {
    error_log("Seasonal Events API Error: " . $e->getMessage());
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>