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

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

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

    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        http_response_code(405);
        echo json_encode(['ok' => false, 'error' => 'Method not allowed']);
        exit;
    }

    $delivery_id = (int)($_POST['delivery_id'] ?? 0);
    $notes = trim((string)($_POST['notes'] ?? ''));
    $signature_data = (string)($_POST['signature_data'] ?? '');

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

    // Must be assigned to 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']]);
    $del = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$del) {
        http_response_code(403);
        echo json_encode(['ok' => false, 'error' => 'Not assigned to this delivery']);
        exit;
    }

    // OPTIONAL: only allow POD if delivered
    if (($del['status'] ?? '') !== 'DELIVERED') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'POD can only be submitted after DELIVERED']);
        exit;
    }

    $baseDir = __DIR__ . '/../uploads/pod';
    if (!is_dir($baseDir)) {
        mkdir($baseDir, 0775, true);
    }

    $ts = date('Ymd_His');
    $photoPath = null;
    $sigPath = null;

    // Photo upload (optional)
    if (!empty($_FILES['photo']) && $_FILES['photo']['error'] === UPLOAD_ERR_OK) {
        $tmp = $_FILES['photo']['tmp_name'];
        $ext = strtolower(pathinfo($_FILES['photo']['name'], PATHINFO_EXTENSION));

        if (!in_array($ext, ['jpg','jpeg','png','webp'], true)) {
            http_response_code(400);
            echo json_encode(['ok' => false, 'error' => 'Photo must be jpg/jpeg/png/webp']);
            exit;
        }

        $fname = "pod_{$delivery_id}_{$ts}." . $ext;
        $dest = $baseDir . '/' . $fname;

        if (!move_uploaded_file($tmp, $dest)) {
            http_response_code(500);
            echo json_encode(['ok' => false, 'error' => 'Failed to save photo']);
            exit;
        }

        $photoPath = 'uploads/pod/' . $fname;
    }

    // Signature (optional - base64 PNG from canvas)
    if ($signature_data !== '' && strpos($signature_data, 'data:image/png;base64,') === 0) {
        $raw = base64_decode(substr($signature_data, strlen('data:image/png;base64,')));
        if ($raw !== false && strlen($raw) > 0) {
            $fname = "sig_{$delivery_id}_{$ts}.png";
            $dest = $baseDir . '/' . $fname;
            file_put_contents($dest, $raw);
            $sigPath = 'uploads/pod/' . $fname;
        }
    }

    if ($photoPath === null && $sigPath === null && $notes === '') {
        http_response_code(400);
        echo json_encode(['ok' => false, 'error' => 'Please provide photo and/or signature and/or notes']);
        exit;
    }

    // Insert POD record
    $ins = $pdo->prepare("
      INSERT INTO delivery_proofs (delivery_id, driver_id, photo_path, signature_path, notes)
      VALUES (:did, :uid, :photo, :sig, :notes)
    ");
    $ins->execute([
        ':did' => $delivery_id,
        ':uid' => (int)$user['id'],
        ':photo' => $photoPath,
        ':sig' => $sigPath,
        ':notes' => ($notes !== '' ? $notes : null),
    ]);

    echo json_encode(['ok' => true, 'id' => (int)$pdo->lastInsertId()]);
    exit;

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