<?php
// ============================================================
// Elegant Work — Calendar Reschedule
// POST: event_id (prefixed: evt-X, jc-X, cl-X), new_date
// ============================================================
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user    = requireAuth();
$db      = getDB();
$uid     = (int)$user['id'];
$eventId = trim(post('event_id', ''));
$newDate = trim(post('new_date', ''));

if (!$eventId || !$newDate) apiError('event_id and new_date are required.', 422);
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $newDate)) apiError('Invalid date format.', 422);
// Sanity-check date
if (!checkdate((int)substr($newDate,5,2),(int)substr($newDate,8,2),(int)substr($newDate,0,4)))
    apiError('Invalid date.', 422);

// ── Custom calendar event ─────────────────────────────────
if (str_starts_with($eventId, 'evt-')) {
    $id = (int)substr($eventId, 4);
    // Only the creator can move their own event
    $row = $db->prepare("SELECT id, created_by FROM calendar_events WHERE id = ? LIMIT 1");
    $row->execute([$id]);
    $ev = $row->fetch();
    if (!$ev) apiError('Event not found.', 404);
    if ((int)$ev['created_by'] !== $uid && (int)$user['role_id'] !== 1)
        apiError('You can only move your own events.', 403);
    $db->prepare("UPDATE calendar_events SET event_date = ? WHERE id = ?")->execute([$newDate, $id]);
    apiSuccess(['id' => $eventId, 'new_date' => $newDate], 'Event rescheduled.');
}

// ── Job card ──────────────────────────────────────────────
if (str_starts_with($eventId, 'jc-')) {
    if (!in_array((int)$user['role_id'], [1, 2, 4, 5]))
        apiError('Insufficient permissions.', 403);
    $id = (int)substr($eventId, 3);
    $row = $db->prepare("SELECT id FROM job_cards WHERE id = ? LIMIT 1");
    $row->execute([$id]);
    if (!$row->fetch()) apiError('Job card not found.', 404);
    $db->prepare("UPDATE job_cards SET scheduled_date = ? WHERE id = ?")->execute([$newDate, $id]);
    apiSuccess(['id' => $eventId, 'new_date' => $newDate], 'Job card rescheduled.');
}

// ── Checklist instance ────────────────────────────────────
if (str_starts_with($eventId, 'cl-')) {
    if (!in_array((int)$user['role_id'], [1, 2, 4, 5]))
        apiError('Insufficient permissions.', 403);
    $id = (int)substr($eventId, 3);
    $row = $db->prepare("SELECT id, status FROM checklist_instances WHERE id = ? LIMIT 1");
    $row->execute([$id]);
    $ci = $row->fetch();
    if (!$ci) apiError('Checklist instance not found.', 404);
    if ($ci['status'] === 'completed') apiError('Cannot reschedule a completed checklist.', 422);
    $db->prepare("UPDATE checklist_instances SET due_date = ? WHERE id = ?")->execute([$newDate, $id]);
    apiSuccess(['id' => $eventId, 'new_date' => $newDate], 'Checklist rescheduled.');
}

apiError('Unsupported event type.', 422);