<?php
require_once __DIR__ . '/../helpers/auth.php';
require_login();

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

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

    $delivery_id = (int)($_GET['delivery_id'] ?? 0);
    if ($delivery_id <= 0) {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Invalid delivery_id']);
        exit;
    }

    // Driver can only view their own assigned delivery POD
    if (($user['role_name'] ?? '') === 'driver') {
        $chk = $pdo->prepare("SELECT id FROM deliveries WHERE id=:id AND assigned_driver_id=:uid LIMIT 1");
        $chk->execute([':id' => $delivery_id, ':uid' => (int)$user['id']]);
        if (!$chk->fetch()) {
            http_response_code(403);
            echo json_encode(['ok' => false, 'error' => 'Forbidden']);
            exit;
        }
    } else {
        // staff/admin allowed
        require_role(['admin','staff']);
    }

    $stmt = $pdo->prepare("
      SELECT dp.id, dp.photo_path, dp.signature_path, dp.notes, dp.created_at,
             u.full_name AS driver_name
      FROM delivery_proofs dp
      JOIN users u ON u.id = dp.driver_id
      WHERE dp.delivery_id = :did
      ORDER BY dp.created_at DESC
    ");
    $stmt->execute([':did' => $delivery_id]);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode(['ok' => true, 'items' => $rows]);
    exit;

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