<?php
// POST /api/calendar/event_save.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireAuth();
$db   = getDB();

$action = post('action', 'create'); // create | update | delete

if ($action === 'delete') {
    $id = (int)post('id', 0);
    if (!$id) apiError('Event ID required.', 422);
    // Only owner can delete
    $stmt = $db->prepare("DELETE FROM calendar_events WHERE id = ? AND created_by = ?");
    $stmt->execute([$id, $user['id']]);
    apiSuccess([], 'Event deleted.');
}

$title     = trim(post('title', ''));
$eventDate = post('event_date', date('Y-m-d'));
if (!$title)     apiError('Title required.', 422);
if (!$eventDate) apiError('Date required.', 422);

$data = [
    post('title'),
    post('description'),
    $eventDate,
    post('event_time') ?: null,
    post('all_day') ? 1 : 0,
    post('event_type', 'event'),
    post('color', 'teal'),
    post('is_shared') ? 1 : 0,
];

if ($action === 'update') {
    $id = (int)post('id', 0);
    if (!$id) apiError('Event ID required.', 422);
    $db->prepare("
        UPDATE calendar_events
        SET title=?, description=?, event_date=?, event_time=?, all_day=?,
            event_type=?, color=?, is_shared=?
        WHERE id=? AND created_by=?
    ")->execute([...$data, $id, $user['id']]);
    apiSuccess(['id' => $id], 'Event updated.');
} else {
    $data[] = $user['id'];
    $db->prepare("
        INSERT INTO calendar_events
            (title, description, event_date, event_time, all_day, event_type, color, is_shared, created_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
    ")->execute($data);
    apiSuccess(['id' => (int)$db->lastInsertId()], 'Event created.', 201);
}
