<?php
/**
 * ================================================
 * PARANDATUD EVENTS API - PUHAS VERSIOON
 * ================================================
 */

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');

// Handle preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// Põhiseadistused
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../includes/functions.php';

session_start();

// Debug logging function
function apiLog($message, $data = null) {
    $logMessage = '[' . date('Y-m-d H:i:s') . '] Events API: ' . $message;
    if ($data) {
        $logMessage .= ' | Data: ' . json_encode($data, JSON_UNESCAPED_UNICODE);
    }
    error_log($logMessage);
}

// Funksioon JSON vastuse saatmiseks
function sendJsonResponse($data, $status = 200) {
    http_response_code($status);
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

// Funksioon vea saatmiseks
function sendError($message, $status = 400) {
    apiLog('ERROR: ' . $message);
    sendJsonResponse(['error' => $message, 'success' => false], $status);
}

// Funksioon edukas vastuse saatmiseks
function sendSuccess($data = [], $message = 'Tegevus õnnestus') {
    apiLog('SUCCESS: ' . $message, ['dataCount' => is_array($data) ? count($data) : 'N/A']);
    sendJsonResponse([
        'success' => true,
        'message' => $message,
        'data' => $data
    ]);
}

// Log API call
apiLog('API called', [
    'method' => $_SERVER['REQUEST_METHOD'],
    'uri' => $_SERVER['REQUEST_URI'],
    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
]);

// Kontrolli sisselogimist
if (!isLoggedIn()) {
    sendError('Sisselogimine nõutav', 401);
}

$current_user_id = $_SESSION['user_id'];
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';

apiLog('Processing request', [
    'user_id' => $current_user_id,
    'method' => $method,
    'action' => $action
]);

try {
    // Ensure events table exists
    $pdo->exec("
        CREATE TABLE IF NOT EXISTS events (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            user_id INTEGER NOT NULL,
            title VARCHAR(255) NOT NULL,
            description TEXT,
            start_datetime TIMESTAMP NOT NULL,
            end_datetime TIMESTAMP,
            all_day BOOLEAN DEFAULT 0,
            location VARCHAR(255),
            category_id INTEGER,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
        )
    ");
    
    switch ($method) {
        case 'GET':
            handleGetRequest($pdo, $current_user_id, $action);
            break;
        case 'POST':
            handlePostRequest($pdo, $current_user_id);
            break;
        case 'PUT':
            handlePutRequest($pdo, $current_user_id);
            break;
        case 'DELETE':
            handleDeleteRequest($pdo, $current_user_id);
            break;
        default:
            sendError('Meetod pole toetatud', 405);
    }
} catch (Exception $e) {
    apiLog('EXCEPTION: ' . $e->getMessage());
    sendError('Serveri viga: ' . $e->getMessage(), 500);
}

/**
 * ======================
 * GET PÄRINGUTE KÄITLEMINE
 * ======================
 */
function handleGetRequest($pdo, $user_id, $action) {
    switch ($action) {
        case 'list':
            getEvents($pdo, $user_id);
            break;
        case 'single':
            getSingleEvent($pdo, $user_id);
            break;
        case 'search':
            searchEvents($pdo, $user_id);
            break;
        default:
            getEvents($pdo, $user_id);
    }
}

/**
 * Lae sündmused
 */
function getEvents($pdo, $user_id) {
    $start_date = $_GET['start'] ?? null;
    $end_date = $_GET['end'] ?? null;
    $category_id = $_GET['category'] ?? null;
    
    try {
        $sql = "
            SELECT 
                e.id,
                e.title,
                e.description,
                e.start_datetime,
                e.end_datetime,
                e.all_day,
                e.location,
                e.category_id,
                e.created_at,
                e.updated_at,
                COALESCE(c.name, 'Kategooriata') as category_name,
                COALESCE(c.color, '#4285F4') as category_color,
                COALESCE(c.icon, '📅') as category_icon
            FROM events e 
            LEFT JOIN event_categories c ON e.category_id = c.id 
            WHERE e.user_id = ?
        ";
        
        $params = [$user_id];
        
        // Add date filtering if provided
        if ($start_date && $end_date) {
            $sql .= " AND DATE(e.start_datetime) BETWEEN ? AND ?";
            $params[] = $start_date;
            $params[] = $end_date;
        }
        
        if ($category_id) {
            $sql .= " AND e.category_id = ?";
            $params[] = $category_id;
        }
        
        $sql .= " ORDER BY e.start_datetime ASC";
        
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $events = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        apiLog('Events loaded', [
            'user_id' => $user_id,
            'count' => count($events),
            'start_date' => $start_date,
            'end_date' => $end_date,
            'category_id' => $category_id
        ]);
        
        sendSuccess($events);
        
    } catch (PDOException $e) {
        apiLog('Events load error: ' . $e->getMessage());
        sendError('Sündmuste laadimine ebaõnnestus: ' . $e->getMessage());
    }
}

/**
 * Lae üks sündmus
 */
function getSingleEvent($pdo, $user_id) {
    $event_id = $_GET['id'] ?? null;
    
    if (!$event_id) {
        sendError('Sündmuse ID on nõutav');
    }
    
    try {
        $stmt = $pdo->prepare("
            SELECT 
                e.*,
                c.name as category_name,
                c.color as category_color,
                c.icon as category_icon
            FROM events e 
            LEFT JOIN event_categories c ON e.category_id = c.id 
            WHERE e.id = ? AND e.user_id = ?
        ");
        $stmt->execute([$event_id, $user_id]);
        $event = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$event) {
            sendError('Sündmust ei leitud', 404);
        }
        
        sendSuccess($event);
        
    } catch (PDOException $e) {
        apiLog('Single event load error: ' . $e->getMessage());
        sendError('Sündmuse laadimine ebaõnnestus');
    }
}

/**
 * Otsi sündmusi
 */
function searchEvents($pdo, $user_id) {
    $query = $_GET['q'] ?? '';
    
    if (strlen($query) < 2) {
        sendError('Otsisõna peab olema vähemalt 2 tähemärki');
    }
    
    try {
        $stmt = $pdo->prepare("
            SELECT 
                e.*,
                c.name as category_name,
                c.color as category_color,
                c.icon as category_icon
            FROM events e 
            LEFT JOIN event_categories c ON e.category_id = c.id 
            WHERE e.user_id = ? AND (
                e.title LIKE ? OR 
                e.description LIKE ? OR 
                e.location LIKE ?
            )
            ORDER BY e.start_datetime ASC
            LIMIT 50
        ");
        
        $searchTerm = '%' . $query . '%';
        $stmt->execute([$user_id, $searchTerm, $searchTerm, $searchTerm]);
        $events = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        apiLog('Events searched', [
            'query' => $query,
            'results' => count($events)
        ]);
        
        sendSuccess($events);
        
    } catch (PDOException $e) {
        apiLog('Search error: ' . $e->getMessage());
        sendError('Otsing ebaõnnestus');
    }
}

/**
 * ======================
 * POST PÄRINGUTE KÄITLEMINE
 * ======================
 */
function handlePostRequest($pdo, $user_id) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    apiLog('POST request received', $input);
    
    if (!$input) {
        sendError('Vigased sisendandmed');
    }
    
    // Valideerib nõutavad väljad
    if (empty($input['title'])) {
        sendError('Sündmuse nimi on nõutav');
    }
    
    if (empty($input['start_datetime'])) {
        sendError('Algusaeg on nõutav');
    }
    
    try {
        // Lisa sündmus
        $stmt = $pdo->prepare("
            INSERT INTO events (
                user_id, title, description, start_datetime, end_datetime, 
                all_day, location, category_id, created_at, updated_at
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
        ");
        
        $stmt->execute([
            $user_id,
            $input['title'],
            $input['description'] ?? null,
            $input['start_datetime'],
            $input['end_datetime'] ?? null,
            isset($input['all_day']) ? (int)$input['all_day'] : 0,
            $input['location'] ?? null,
            !empty($input['category_id']) ? $input['category_id'] : null
        ]);
        
        $event_id = $pdo->lastInsertId();
        
        apiLog('Event created', [
            'event_id' => $event_id,
            'user_id' => $user_id,
            'title' => $input['title']
        ]);
        
        sendSuccess(['id' => $event_id], 'Sündmus edukalt lisatud!');
        
    } catch (PDOException $e) {
        apiLog('Event creation error: ' . $e->getMessage());
        sendError('Sündmuse lisamine ebaõnnestus: ' . $e->getMessage());
    }
}

/**
 * ======================
 * PUT PÄRINGUTE KÄITLEMINE
 * ======================
 */
function handlePutRequest($pdo, $user_id) {
    $input = json_decode(file_get_contents('php://input'), true);
    
    apiLog('PUT request received', $input);
    
    if (!$input || empty($input['id'])) {
        sendError('Sündmuse ID on nõutav');
    }
    
    $event_id = $input['id'];
    
    // Kontrolli, kas sündmus kuulub kasutajale
    $stmt = $pdo->prepare("SELECT id FROM events WHERE id = ? AND user_id = ?");
    $stmt->execute([$event_id, $user_id]);
    
    if (!$stmt->fetch()) {
        sendError('Sündmust ei leitud või puuduvad õigused', 404);
    }
    
    try {
        // Uuenda sündmust
        $stmt = $pdo->prepare("
            UPDATE events SET 
                title = ?, 
                description = ?, 
                start_datetime = ?, 
                end_datetime = ?, 
                all_day = ?, 
                location = ?, 
                category_id = ?,
                updated_at = CURRENT_TIMESTAMP
            WHERE id = ? AND user_id = ?
        ");
        
        $stmt->execute([
            $input['title'],
            $input['description'] ?? null,
            $input['start_datetime'],
            $input['end_datetime'] ?? null,
            isset($input['all_day']) ? (int)$input['all_day'] : 0,
            $input['location'] ?? null,
            !empty($input['category_id']) ? $input['category_id'] : null,
            $event_id,
            $user_id
        ]);
        
        apiLog('Event updated', [
            'event_id' => $event_id,
            'user_id' => $user_id,
            'title' => $input['title']
        ]);
        
        sendSuccess(['id' => $event_id], 'Sündmus edukalt uuendatud!');
        
    } catch (PDOException $e) {
        apiLog('Event update error: ' . $e->getMessage());
        sendError('Sündmuse uuendamine ebaõnnestus: ' . $e->getMessage());
    }
}

/**
 * ======================
 * DELETE PÄRINGUTE KÄITLEMINE
 * ======================
 */
function handleDeleteRequest($pdo, $user_id) {
    $input = json_decode(file_get_contents('php://input'), true);
    $event_id = $input['id'] ?? $_GET['id'] ?? null;
    
    apiLog('DELETE request received', ['event_id' => $event_id]);
    
    if (!$event_id) {
        sendError('Sündmuse ID on nõutav');
    }
    
    try {
        // Kontrolli omandiõigust
        $stmt = $pdo->prepare("SELECT title FROM events WHERE id = ? AND user_id = ?");
        $stmt->execute([$event_id, $user_id]);
        $event = $stmt->fetch();
        
        if (!$event) {
            sendError('Sündmust ei leitud või puuduvad õigused', 404);
        }
        
        // Kustuta sündmus
        $stmt = $pdo->prepare("DELETE FROM events WHERE id = ? AND user_id = ?");
        $stmt->execute([$event_id, $user_id]);
        
        apiLog('Event deleted', [
            'event_id' => $event_id,
            'user_id' => $user_id,
            'title' => $event['title']
        ]);
        
        sendSuccess([], 'Sündmus edukalt kustutatud!');
        
    } catch (PDOException $e) {
        apiLog('Event deletion error: ' . $e->getMessage());
        sendError('Sündmuse kustutamine ebaõnnestus: ' . $e->getMessage());
    }
}
?>