<?php
// Set default timezone to Africa Central Time (CAT, UTC+2) for Harare, Zimbabwe
date_default_timezone_set('Africa/Harare');

require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../config/rbac.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/middleware.php';

// Check if user is logged in for write operations
if ($_SERVER['REQUEST_METHOD'] !== 'GET' && !isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$db = getDB();
$userId = $_SESSION['user_id'];
$method = $_SERVER['REQUEST_METHOD'];

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

try {
    switch ($method) {
        case 'GET':
            // Get events for a specific date or all events
            if (isset($_GET['date'])) {
                $date = $_GET['date'];
                $stmt = $db->prepare("SELECT * FROM calendar_events WHERE event_date = ? ORDER BY created_at DESC");
                $stmt->execute([$date]);
            } else {
                // Get all events (for admin)
                if (hasRole('admin')) {
                    $stmt = $db->query("SELECT ce.*, u.username as creator_name FROM calendar_events ce LEFT JOIN users u ON ce.creator_id = u.id ORDER BY event_date DESC, created_at DESC");
                } else {
                    // Regular users see all events
                    $stmt = $db->query("SELECT * FROM calendar_events ORDER BY event_date DESC, created_at DESC");
                }
            }
            $events = $stmt->fetchAll(PDO::FETCH_ASSOC);
            echo json_encode(['success' => true, 'events' => $events]);
            break;

        case 'POST':
            // Create new event
            $data = json_decode(file_get_contents('php://input'), true);

            if (!$data || !isset($data['title']) || !isset($data['event_date'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'Missing required fields']);
                exit;
            }

            $stmt = $db->prepare("INSERT INTO calendar_events (title, description, event_date, event_time, creator_id) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([
                $data['title'],
                $data['description'] ?? '',
                $data['event_date'],
                $data['event_time'] ?? '09:00',
                $userId
            ]);

            $eventId = $db->lastInsertId();

            // Send notification for new event
            if (function_exists('sendCalendarNotification')) {
                sendCalendarNotification('event_created', $eventId);
            }

            echo json_encode(['success' => true, 'event_id' => $eventId]);
            break;

        case 'PUT':
            // Update event (admin only)
            if (!hasRole('admin')) {
                http_response_code(403);
                echo json_encode(['success' => false, 'error' => 'Admin access required']);
                exit;
            }

            $data = json_decode(file_get_contents('php://input'), true);

            if (!$data || !isset($data['id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'Event ID required']);
                exit;
            }

            $updateFields = [];
            $params = [];

            if (isset($data['title'])) {
                $updateFields[] = "title = ?";
                $params[] = $data['title'];
            }

            if (isset($data['description'])) {
                $updateFields[] = "description = ?";
                $params[] = $data['description'];
            }

            if (isset($data['event_date'])) {
                $updateFields[] = "event_date = ?";
                $params[] = $data['event_date'];
            }

            if (isset($data['event_time'])) {
                $updateFields[] = "event_time = ?";
                $params[] = $data['event_time'];
            }

            if (empty($updateFields)) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'No fields to update']);
                exit;
            }

            $params[] = $data['id'];
            $stmt = $db->prepare("UPDATE calendar_events SET " . implode(', ', $updateFields) . " WHERE id = ?");
            $stmt->execute($params);

            // Send notification for updated event
            if (function_exists('sendCalendarNotification')) {
                sendCalendarNotification('event_updated', $data['id']);
            }

            echo json_encode(['success' => true]);
            break;

        case 'DELETE':
            // Delete event (admin only)
            if (!hasRole('admin')) {
                http_response_code(403);
                echo json_encode(['success' => false, 'error' => 'Admin access required']);
                exit;
            }

            if (!isset($_GET['id'])) {
                http_response_code(400);
                echo json_encode(['success' => false, 'error' => 'Event ID required']);
                exit;
            }

            $stmt = $db->prepare("DELETE FROM calendar_events WHERE id = ?");
            $stmt->execute([$_GET['id']]);

            echo json_encode(['success' => true]);
            break;

        default:
            http_response_code(405);
            echo json_encode(['success' => false, 'error' => 'Method not allowed']);
            break;
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
?>