<?php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['driver']);

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

try {
    $pdo = db();
    $user = current_user();

    $data = json_decode(file_get_contents('php://input'), true);
    if (!is_array($data)) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid JSON']);
        exit;
    }

    $delivery_id = (int)($data['delivery_id'] ?? 0);
    $status = trim((string)($data['status'] ?? ''));

    $allowed = ['PICKED_UP','IN_TRANSIT','DELIVERED'];
    if ($delivery_id <= 0 || !in_array($status, $allowed, true)) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid delivery_id or status']);
        exit;
    }

    // Must be assigned to this driver
    $stmt = $pdo->prepare("
      SELECT id, status
      FROM deliveries
      WHERE id = :id AND assigned_driver_id = :uid
      LIMIT 1
    ");
    $stmt->execute([':id' => $delivery_id, ':uid' => (int)$user['id']]);
    $d = $stmt->fetch();

    if (!$d) {
        http_response_code(404);
        echo json_encode(['ok' => false, 'error' => 'Delivery not found or not assigned to you']);
        exit;
    }

    // Update status + timestamps
    if ($status === 'PICKED_UP') {
        $upd = $pdo->prepare("
          UPDATE deliveries
          SET status='PICKED_UP',
              picked_up_at = COALESCE(picked_up_at, NOW())
          WHERE id=:id
        ");
        $upd->execute([':id' => $delivery_id]);
    }

    if ($status === 'IN_TRANSIT') {
        $upd = $pdo->prepare("
          UPDATE deliveries
          SET status='IN_TRANSIT',
              in_transit_at = COALESCE(in_transit_at, NOW())
          WHERE id=:id
        ");
        $upd->execute([':id' => $delivery_id]);
    }

    if ($status === 'DELIVERED') {
        $upd = $pdo->prepare("
          UPDATE deliveries
          SET status='DELIVERED',
              delivered_at = COALESCE(delivered_at, NOW())
          WHERE id=:id
        ");
        $upd->execute([':id' => $delivery_id]);
    }

    // Return fresh delivery timeline
    $out = $pdo->prepare("
      SELECT status, picked_up_at, in_transit_at, delivered_at
      FROM deliveries
      WHERE id=:id
      LIMIT 1
    ");
    $out->execute([':id' => $delivery_id]);
    $row = $out->fetch();

    echo json_encode([
        'ok' => true,
        'status' => $row['status'],
        'picked_up_at' => $row['picked_up_at'],
        'in_transit_at' => $row['in_transit_at'],
        'delivered_at' => $row['delivered_at'],
        'updated_at' => date('Y-m-d H:i:s')
    ]);
    exit;

} catch (Throwable $e) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
    exit;
}
