<?php
require_once __DIR__ . '/../helpers/auth.php';
require_once __DIR__ . '/../helpers/audit.php';
require_once __DIR__ . '/../helpers/inventory.php';
require_role(['admin', 'staff']);

$pdo = db();
$title = 'Delivery Details - IMS';
$user = current_user();

function h(?string $value): string
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function get_int(string $key): int
{
    return (int)($_GET[$key] ?? 0);
}

function post_int(string $key): int
{
    return (int)($_POST[$key] ?? 0);
}

function post_str(string $key): string
{
    return trim((string)($_POST[$key] ?? ''));
}

function normalize_optional_datetime(string $input): ?string
{
    $value = trim($input);
    if ($value === '') {
        return null;
    }
    $value = str_replace('T', ' ', $value);
    if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $value)) {
        return $value . ':00';
    }
    if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/', $value)) {
        return $value;
    }
    return null;
}

function format_datetime_local(?string $value): string
{
    if (!$value) {
        return '';
    }
    return substr(str_replace(' ', 'T', $value), 0, 16);
}

function status_badge(string $status): string
{
    $safe = preg_replace('/[^A-Z_]+/', '', strtoupper($status)) ?: 'PENDING';
    return '<span class="status-pill status-' . h($safe) . '">' . h(str_replace('_', ' ', $safe)) . '</span>';
}

$deliveryId = get_int('id');
if ($deliveryId <= 0) {
    http_response_code(400);
    die('Invalid delivery ID.');
}

function load_delivery_screen_state(PDO $pdo, int $deliveryId): array
{
    $delivery = delivery_load($pdo, $deliveryId);
    if (!$delivery) {
        return [];
    }

    $items = delivery_items($pdo, $deliveryId);
    $routeStats = delivery_route_stats($pdo, $deliveryId);
    $latestLocation = delivery_latest_location($pdo, $deliveryId);
    $stockDeducted = delivery_stock_already_deducted($pdo, $deliveryId);

    $proofStmt = $pdo->prepare("\n        SELECT dp.*, u.full_name AS driver_name\n        FROM delivery_proofs dp\n        LEFT JOIN users u ON u.id = dp.driver_id\n        WHERE dp.delivery_id = :delivery_id\n        ORDER BY dp.created_at DESC, dp.id DESC\n    ");
    $proofStmt->execute([':delivery_id' => $deliveryId]);
    $proofs = $proofStmt->fetchAll(PDO::FETCH_ASSOC);

    return [
        'delivery' => $delivery,
        'items' => $items,
        'route_stats' => $routeStats,
        'latest_location' => $latestLocation,
        'stock_deducted' => $stockDeducted,
        'proofs' => $proofs,
    ];
}

$drivers = $pdo->query("\n    SELECT u.id, u.full_name\n    FROM users u\n    INNER JOIN roles r ON r.id = u.role_id\n    WHERE r.name = 'driver' AND u.is_active = 1\n    ORDER BY u.full_name ASC\n")->fetchAll(PDO::FETCH_ASSOC);

$products = $pdo->query("\n    SELECT\n        p.id, p.sku, p.name, p.unit, p.barcode_value,\n        COALESCE(stock_summary.current_stock, p.quantity_on_hand, 0) AS current_stock\n    FROM products p\n    LEFT JOIN (\n        SELECT m.product_id, " . inventory_stock_expression('m') . " AS current_stock\n        FROM inventory_movements m\n        GROUP BY m.product_id\n    ) stock_summary ON stock_summary.product_id = p.id\n    WHERE p.is_active = 1\n    ORDER BY p.name ASC\n")->fetchAll(PDO::FETCH_ASSOC);

$screen = load_delivery_screen_state($pdo, $deliveryId);
$delivery = $screen['delivery'] ?? null;
if (!$delivery) {
    http_response_code(404);
    die('Delivery not found.');
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = post_str('action');
    $canEditItems = !$screen['stock_deducted'] && !in_array((string)$delivery['status'], ['DELIVERED', 'CANCELLED'], true);
    $canEditDetails = !in_array((string)$delivery['status'], ['DELIVERED', 'CANCELLED'], true);

    if ($action === 'update_details') {
        if (!$canEditDetails) {
            $error = 'Completed or cancelled deliveries are locked for route edits.';
        } else {
            $driverId = post_int('assigned_driver_id') ?: null;
            $pickupAddress = post_str('pickup_address');
            $dropoffAddress = post_str('dropoff_address');
            $pickupLat = post_str('pickup_lat');
            $pickupLng = post_str('pickup_lng');
            $dropoffLat = post_str('dropoff_lat');
            $dropoffLng = post_str('dropoff_lng');
            $scheduledAt = normalize_optional_datetime(post_str('scheduled_at'));
            $notes = post_str('notes');

            if ($pickupAddress === '' || $dropoffAddress === '') {
                $error = 'Pickup and dropoff address are required.';
            } else {
                try {
                    $nextStatus = (string)$delivery['status'];
                    if ($driverId && $nextStatus === 'PENDING') {
                        $nextStatus = 'ASSIGNED';
                    }
                    if (!$driverId && $nextStatus === 'ASSIGNED') {
                        $nextStatus = 'PENDING';
                    }

                    $stmt = $pdo->prepare("\n                        UPDATE deliveries\n                        SET assigned_driver_id = :assigned_driver_id,\n                            status = :status,\n                            pickup_address = :pickup_address,\n                            dropoff_address = :dropoff_address,\n                            pickup_lat = :pickup_lat,\n                            pickup_lng = :pickup_lng,\n                            dropoff_lat = :dropoff_lat,\n                            dropoff_lng = :dropoff_lng,\n                            notes = :notes,\n                            scheduled_at = :scheduled_at\n                        WHERE id = :id\n                        LIMIT 1\n                    ");
                    $stmt->execute([
                        ':assigned_driver_id' => $driverId,
                        ':status' => $nextStatus,
                        ':pickup_address' => $pickupAddress,
                        ':dropoff_address' => $dropoffAddress,
                        ':pickup_lat' => $pickupLat !== '' ? (float)$pickupLat : null,
                        ':pickup_lng' => $pickupLng !== '' ? (float)$pickupLng : null,
                        ':dropoff_lat' => $dropoffLat !== '' ? (float)$dropoffLat : null,
                        ':dropoff_lng' => $dropoffLng !== '' ? (float)$dropoffLng : null,
                        ':notes' => $notes !== '' ? $notes : null,
                        ':scheduled_at' => $scheduledAt,
                        ':id' => $deliveryId,
                    ]);

                    audit_log(
                        'UPDATE_DELIVERY',
                        'deliveries',
                        (string)$deliveryId,
                        json_encode([
                            'assigned_driver_id' => $driverId,
                            'status' => $nextStatus,
                        ], JSON_UNESCAPED_SLASHES)
                    );
                    $success = 'Delivery details updated.';
                } catch (Throwable $e) {
                    $error = 'Failed to update delivery: ' . $e->getMessage();
                }
            }
        }
    }

    if ($action === 'add_item') {
        if (!$canEditItems) {
            $error = 'Items cannot be changed after stock has been released or the route is closed.';
        } else {
            $productId = post_int('product_id');
            $qty = post_int('quantity');
            if ($productId <= 0 || $qty <= 0) {
                $error = 'Select a product and quantity greater than zero.';
            } else {
                try {
                    $stmt = $pdo->prepare("\n                        INSERT INTO delivery_items (delivery_id, product_id, quantity)\n                        VALUES (:delivery_id, :product_id, :quantity)\n                        ON DUPLICATE KEY UPDATE quantity = quantity + VALUES(quantity)\n                    ");
                    $stmt->execute([
                        ':delivery_id' => $deliveryId,
                        ':product_id' => $productId,
                        ':quantity' => $qty,
                    ]);
                    audit_log('ADD_DELIVERY_ITEM', 'delivery_items', (string)$deliveryId, json_encode(['product_id' => $productId, 'quantity' => $qty], JSON_UNESCAPED_SLASHES));
                    $success = 'Item added to the delivery.';
                } catch (Throwable $e) {
                    $error = 'Failed to add item: ' . $e->getMessage();
                }
            }
        }
    }

    if ($action === 'delete_item') {
        if (!$canEditItems) {
            $error = 'Items cannot be changed after stock has been released or the route is closed.';
        } else {
            $itemId = post_int('item_id');
            if ($itemId <= 0) {
                $error = 'Invalid item.';
            } else {
                try {
                    $stmt = $pdo->prepare('DELETE FROM delivery_items WHERE id = :id AND delivery_id = :delivery_id LIMIT 1');
                    $stmt->execute([
                        ':id' => $itemId,
                        ':delivery_id' => $deliveryId,
                    ]);
                    audit_log('REMOVE_DELIVERY_ITEM', 'delivery_items', (string)$deliveryId, json_encode(['item_id' => $itemId], JSON_UNESCAPED_SLASHES));
                    $success = 'Item removed from the delivery.';
                } catch (Throwable $e) {
                    $error = 'Failed to remove item: ' . $e->getMessage();
                }
            }
        }
    }

    if ($action === 'update_status') {
        $newStatus = strtoupper(post_str('status'));
        if ($newStatus === '') {
            $error = 'Choose a status.';
        } else {
            try {
                $result = delivery_update_status($pdo, $deliveryId, $newStatus, (int)($user['id'] ?? 0));
                audit_log(
                    'UPDATE_DELIVERY_STATUS',
                    'deliveries',
                    (string)$deliveryId,
                    json_encode([
                        'status' => $newStatus,
                        'stock_deducted' => !empty($result['stock_deducted']),
                    ], JSON_UNESCAPED_SLASHES)
                );
                $success = 'Delivery status updated to ' . str_replace('_', ' ', $newStatus) . (!empty($result['stock_deducted']) ? ' and inventory was released.' : '.');
            } catch (Throwable $e) {
                $error = $e->getMessage();
            }
        }
    }

    $screen = load_delivery_screen_state($pdo, $deliveryId);
    $delivery = $screen['delivery'] ?? null;
}

$items = $screen['items'] ?? [];
$routeStats = $screen['route_stats'] ?? ['point_count' => 0, 'first_recorded_at' => null, 'last_recorded_at' => null];
$latestLocation = $screen['latest_location'] ?? null;
$stockDeducted = (bool)($screen['stock_deducted'] ?? false);
$proofs = $screen['proofs'] ?? [];
$canEditItems = !$stockDeducted && !in_array((string)$delivery['status'], ['DELIVERED', 'CANCELLED'], true);
$canEditDetails = !in_array((string)$delivery['status'], ['DELIVERED', 'CANCELLED'], true);
$totalQty = 0;
foreach ($items as $item) {
    $totalQty += (int)$item['quantity'];
}
$statusChoices = ['PENDING', 'ASSIGNED', 'PICKED_UP', 'IN_TRANSIT', 'DELIVERED', 'CANCELLED'];

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>

<main class="col-12 col-lg-10 app-content">
  <div class="page-head">
    <div>
      <div class="page-kicker">Delivery detail</div>
      <h1 class="page-title"><?= h((string)$delivery['delivery_code']) ?></h1>
      <p class="page-subtitle">Review route details, update the delivery flow, manage items before dispatch closes, and inspect live tracking and proof of delivery in one place.</p>
    </div>
    <div class="d-flex flex-wrap gap-2">
      <a class="btn btn-outline-secondary" href="deliveries.php">Back to deliveries</a>
      <a class="btn btn-dark" href="map_live.php?id=<?= (int)$deliveryId ?>">Open live map</a>
    </div>
  </div>

  <?php if ($error !== ''): ?>
    <div class="alert alert-danger mb-3"><?= h($error) ?></div>
  <?php endif; ?>
  <?php if ($success !== ''): ?>
    <div class="alert alert-success mb-3"><?= h($success) ?></div>
  <?php endif; ?>

  <div class="row g-3 mb-3">
    <div class="col-12 col-md-6 col-xl-3">
      <div class="stat-card">
        <div class="stat-label">Status</div>
        <div class="mt-2"><?= status_badge((string)$delivery['status']) ?></div>
        <div class="stat-sub">Driver: <?= h($delivery['driver_name'] ?: 'Unassigned') ?></div>
      </div>
    </div>
    <div class="col-12 col-md-6 col-xl-3">
      <div class="stat-card">
        <div class="stat-label">Items</div>
        <div class="stat-value"><?= count($items) ?></div>
        <div class="stat-sub">Total quantity <?= $totalQty ?></div>
      </div>
    </div>
    <div class="col-12 col-md-6 col-xl-3">
      <div class="stat-card">
        <div class="stat-label">GPS points</div>
        <div class="stat-value"><?= (int)$routeStats['point_count'] ?></div>
        <div class="stat-sub">Last ping <?= h($routeStats['last_recorded_at'] ?: 'No GPS yet') ?></div>
      </div>
    </div>
    <div class="col-12 col-md-6 col-xl-3">
      <div class="stat-card">
        <div class="stat-label">Inventory release</div>
        <div class="mt-2"><?= $stockDeducted ? '<span class="status-pill status-ok">Released</span>' : '<span class="status-pill status-neutral">Pending</span>' ?></div>
        <div class="stat-sub">Stock is deducted once when delivery is completed.</div>
      </div>
    </div>
  </div>

  <div class="row g-3">
    <div class="col-12 col-xl-4">
      <div class="card mb-3">
        <div class="card-body p-4">
          <div class="d-flex justify-content-between align-items-start mb-3">
            <div>
              <h5 class="mb-1">Route summary</h5>
              <div class="text-muted small">Customer, addresses, assigned driver, and scheduling.</div>
            </div>
            <div><?= status_badge((string)$delivery['status']) ?></div>
          </div>

          <div class="metric-inline"><span>Customer</span><strong><?= h($delivery['customer_name'] ?: 'No customer') ?></strong></div>
          <div class="metric-inline"><span>Driver</span><strong><?= h($delivery['driver_name'] ?: 'Unassigned') ?></strong></div>
          <div class="metric-inline"><span>Scheduled</span><strong><?= h($delivery['scheduled_at'] ?: 'Not scheduled') ?></strong></div>
          <div class="metric-inline"><span>Created</span><strong><?= h((string)$delivery['created_at']) ?></strong></div>
          <div class="soft-panel mt-3">
            <div class="fw-semibold mb-2">Pickup</div>
            <div class="small"><?= h((string)$delivery['pickup_address']) ?></div>
            <?php if ($delivery['pickup_lat'] !== null && $delivery['pickup_lng'] !== null): ?>
              <div class="small text-muted mt-1"><?= h((string)$delivery['pickup_lat']) ?>, <?= h((string)$delivery['pickup_lng']) ?></div>
            <?php endif; ?>
          </div>
          <div class="soft-panel mt-3">
            <div class="fw-semibold mb-2">Dropoff</div>
            <div class="small"><?= h((string)$delivery['dropoff_address']) ?></div>
            <?php if ($delivery['dropoff_lat'] !== null && $delivery['dropoff_lng'] !== null): ?>
              <div class="small text-muted mt-1"><?= h((string)$delivery['dropoff_lat']) ?>, <?= h((string)$delivery['dropoff_lng']) ?></div>
            <?php endif; ?>
          </div>
          <div class="soft-panel mt-3">
            <div class="fw-semibold mb-2">Latest GPS</div>
            <?php if ($latestLocation): ?>
              <div class="small"><?= h((string)$latestLocation['recorded_at']) ?></div>
              <div class="small text-muted"><?= h((string)$latestLocation['lat']) ?>, <?= h((string)$latestLocation['lng']) ?></div>
              <div class="small text-muted">Accuracy <?= $latestLocation['accuracy_m'] !== null ? h((string)$latestLocation['accuracy_m']) . ' m' : 'n/a' ?> · Speed <?= $latestLocation['speed_mps'] !== null ? h((string)$latestLocation['speed_mps']) . ' m/s' : 'n/a' ?></div>
            <?php else: ?>
              <div class="small text-muted">No location updates recorded yet.</div>
            <?php endif; ?>
          </div>
        </div>
      </div>

      <div class="card">
        <div class="card-body p-4">
          <h5 class="mb-3">Timeline</h5>
          <div class="timeline">
            <div class="timeline-item is-done">
              <div class="fw-semibold">Created</div>
              <div class="timeline-time"><?= h((string)$delivery['created_at']) ?></div>
            </div>
            <div class="timeline-item<?= $delivery['scheduled_at'] ? ' is-done' : '' ?>">
              <div class="fw-semibold">Scheduled</div>
              <div class="timeline-time"><?= h($delivery['scheduled_at'] ?: 'Not scheduled') ?></div>
            </div>
            <div class="timeline-item<?= $delivery['picked_up_at'] ? ' is-done' : '' ?>">
              <div class="fw-semibold">Picked up</div>
              <div class="timeline-time"><?= h($delivery['picked_up_at'] ?: 'Pending') ?></div>
            </div>
            <div class="timeline-item<?= $delivery['in_transit_at'] ? ' is-done' : '' ?>">
              <div class="fw-semibold">In transit</div>
              <div class="timeline-time"><?= h($delivery['in_transit_at'] ?: 'Pending') ?></div>
            </div>
            <div class="timeline-item<?= $delivery['delivered_at'] ? ' is-done' : '' ?>">
              <div class="fw-semibold">Delivered</div>
              <div class="timeline-time"><?= h($delivery['delivered_at'] ?: 'Pending') ?></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="col-12 col-xl-8">
      <div class="card mb-3 map-panel">
        <div class="card-body p-4">
          <div class="d-flex justify-content-between align-items-start mb-3">
            <div>
              <h5 class="mb-1">Tracking map</h5>
              <div class="text-muted small">Pickup, dropoff, driver trail, and latest ping.</div>
            </div>
            <div class="text-muted small">Auto refresh every 5 seconds</div>
          </div>
          <div id="deliveryMap" class="map-canvas" style="min-height: 360px;"></div>
        </div>
      </div>

      <div class="row g-3 mb-3">
        <div class="col-12 col-lg-6">
          <div class="card h-100">
            <div class="card-body p-4">
              <h5 class="mb-3">Update route details</h5>
              <?php if (!$canEditDetails): ?>
                <div class="alert alert-warning mb-0">This delivery is closed, so route details are locked.</div>
              <?php else: ?>
                <form method="post">
                  <input type="hidden" name="action" value="update_details">
                  <div class="row g-3">
                    <div class="col-12 col-md-6">
                      <label class="form-label">Assigned driver</label>
                      <select class="form-select" name="assigned_driver_id">
                        <option value="0">Assign later</option>
                        <?php foreach ($drivers as $driverRow): ?>
                          <option value="<?= (int)$driverRow['id'] ?>" <?= (int)($delivery['assigned_driver_id'] ?? 0) === (int)$driverRow['id'] ? 'selected' : '' ?>><?= h($driverRow['full_name']) ?></option>
                        <?php endforeach; ?>
                      </select>
                    </div>
                    <div class="col-12 col-md-6">
                      <label class="form-label">Scheduled time</label>
                      <input class="form-control" type="datetime-local" name="scheduled_at" value="<?= h(format_datetime_local($delivery['scheduled_at'] ?? null)) ?>">
                    </div>
                    <div class="col-12">
                      <label class="form-label">Pickup address</label>
                      <textarea class="form-control" name="pickup_address" rows="2" required><?= h((string)$delivery['pickup_address']) ?></textarea>
                    </div>
                    <div class="col-12">
                      <label class="form-label">Dropoff address</label>
                      <textarea class="form-control" name="dropoff_address" rows="2" required><?= h((string)$delivery['dropoff_address']) ?></textarea>
                    </div>
                    <div class="col-6 col-md-3">
                      <label class="form-label">Pickup lat</label>
                      <input class="form-control" type="number" step="0.0000001" name="pickup_lat" value="<?= h($delivery['pickup_lat'] !== null ? (string)$delivery['pickup_lat'] : '') ?>">
                    </div>
                    <div class="col-6 col-md-3">
                      <label class="form-label">Pickup lng</label>
                      <input class="form-control" type="number" step="0.0000001" name="pickup_lng" value="<?= h($delivery['pickup_lng'] !== null ? (string)$delivery['pickup_lng'] : '') ?>">
                    </div>
                    <div class="col-6 col-md-3">
                      <label class="form-label">Dropoff lat</label>
                      <input class="form-control" type="number" step="0.0000001" name="dropoff_lat" value="<?= h($delivery['dropoff_lat'] !== null ? (string)$delivery['dropoff_lat'] : '') ?>">
                    </div>
                    <div class="col-6 col-md-3">
                      <label class="form-label">Dropoff lng</label>
                      <input class="form-control" type="number" step="0.0000001" name="dropoff_lng" value="<?= h($delivery['dropoff_lng'] !== null ? (string)$delivery['dropoff_lng'] : '') ?>">
                    </div>
                    <div class="col-12">
                      <label class="form-label">Notes</label>
                      <textarea class="form-control" name="notes" rows="3" placeholder="Handling notes or customer remarks"><?= h((string)($delivery['notes'] ?? '')) ?></textarea>
                    </div>
                  </div>
                  <div class="d-grid mt-3">
                    <button class="btn btn-dark" type="submit">Save route details</button>
                  </div>
                </form>
              <?php endif; ?>
            </div>
          </div>
        </div>
        <div class="col-12 col-lg-6">
          <div class="card h-100">
            <div class="card-body p-4">
              <h5 class="mb-3">Update status</h5>
              <form method="post">
                <input type="hidden" name="action" value="update_status">
                <label class="form-label">Current status</label>
                <div class="mb-3"><?= status_badge((string)$delivery['status']) ?></div>
                <label class="form-label">Next status</label>
                <select class="form-select" name="status">
                  <?php foreach ($statusChoices as $statusChoice): ?>
                    <option value="<?= h($statusChoice) ?>" <?= strtoupper((string)$delivery['status']) === $statusChoice ? 'selected' : '' ?>><?= h(str_replace('_', ' ', $statusChoice)) ?></option>
                  <?php endforeach; ?>
                </select>
                <div class="soft-panel mt-3">
                  <div class="small text-muted">When changed to <strong>DELIVERED</strong>, item stock is deducted once from inventory using the delivery reference.</div>
                </div>
                <div class="d-grid mt-3">
                  <button class="btn btn-dark" type="submit">Save status</button>
                </div>
              </form>
            </div>
          </div>
        </div>
      </div>

      <div class="card mb-3">
        <div class="card-body p-4">
          <div class="d-flex justify-content-between align-items-start mb-3">
            <div>
              <h5 class="mb-1">Delivery items</h5>
              <div class="text-muted small">Requested quantity versus current stock before release.</div>
            </div>
            <?php if ($stockDeducted): ?>
              <span class="status-pill status-ok">Inventory released</span>
            <?php endif; ?>
          </div>

          <div class="table-responsive">
            <table class="table align-middle">
              <thead>
                <tr>
                  <th>Product</th>
                  <th class="text-end">Delivery qty</th>
                  <th class="text-end">Current stock</th>
                  <th>Scan code</th>
                  <th class="text-end">Action</th>
                </tr>
              </thead>
              <tbody>
                <?php if (!$items): ?>
                  <tr><td colspan="5" class="text-muted">No items added yet.</td></tr>
                <?php endif; ?>
                <?php foreach ($items as $item): ?>
                  <?php
                    $needed = (int)$item['quantity'];
                    $currentStock = (int)$item['current_stock'];
                    $enough = $stockDeducted || $currentStock >= $needed;
                  ?>
                  <tr>
                    <td>
                      <div class="fw-semibold"><?= h((string)$item['name']) ?></div>
                      <div class="small text-muted"><?= h((string)$item['sku']) ?><?= !empty($item['unit']) ? ' · ' . h((string)$item['unit']) : '' ?></div>
                    </td>
                    <td class="text-end fw-semibold"><?= $needed ?></td>
                    <td class="text-end">
                      <span class="<?= $enough ? 'text-success' : 'text-danger' ?> fw-semibold"><?= $currentStock ?></span>
                    </td>
                    <td>
                      <?php if (!empty($item['barcode_value'])): ?>
                        <span class="code-chip"><?= h((string)$item['barcode_value']) ?></span>
                      <?php else: ?>
                        <span class="code-chip"><?= h((string)$item['sku']) ?></span>
                      <?php endif; ?>
                    </td>
                    <td class="text-end">
                      <?php if ($canEditItems): ?>
                        <form method="post" class="d-inline">
                          <input type="hidden" name="action" value="delete_item">
                          <input type="hidden" name="item_id" value="<?= (int)$item['id'] ?>">
                          <button class="btn btn-sm btn-outline-danger" type="submit">Remove</button>
                        </form>
                      <?php else: ?>
                        <span class="text-muted small">Locked</span>
                      <?php endif; ?>
                    </td>
                  </tr>
                <?php endforeach; ?>
              </tbody>
            </table>
          </div>

          <?php if ($canEditItems): ?>
            <div class="soft-panel mt-3">
              <form method="post" class="row g-3 align-items-end">
                <input type="hidden" name="action" value="add_item">
                <div class="col-12 col-md-8">
                  <label class="form-label">Product</label>
                  <select class="form-select" name="product_id" required>
                    <option value="0">Select product</option>
                    <?php foreach ($products as $product): ?>
                      <option value="<?= (int)$product['id'] ?>">
                        <?= h($product['name']) ?> (<?= h($product['sku']) ?><?= !empty($product['barcode_value']) ? ' · ' . h($product['barcode_value']) : '' ?>) · Stock <?= (int)$product['current_stock'] ?>
                      </option>
                    <?php endforeach; ?>
                  </select>
                </div>
                <div class="col-12 col-md-2">
                  <label class="form-label">Quantity</label>
                  <input class="form-control" type="number" min="1" step="1" name="quantity" required>
                </div>
                <div class="col-12 col-md-2 d-grid">
                  <button class="btn btn-dark" type="submit">Add</button>
                </div>
              </form>
            </div>
          <?php else: ?>
            <div class="alert alert-warning mt-3 mb-0">Items are locked because the delivery is closed or stock has already been released.</div>
          <?php endif; ?>
        </div>
      </div>

      <div class="card">
        <div class="card-body p-4">
          <div class="d-flex justify-content-between align-items-start mb-3">
            <div>
              <h5 class="mb-1">Proof of delivery</h5>
              <div class="text-muted small">Submitted photos, signatures, and delivery notes from the driver.</div>
            </div>
            <div class="small text-muted"><?= count($proofs) ?> submission(s)</div>
          </div>

          <?php if (!$proofs): ?>
            <div class="text-muted">No proof submitted yet.</div>
          <?php else: ?>
            <div class="row g-3">
              <?php foreach ($proofs as $proof): ?>
                <div class="col-12 col-lg-6">
                  <div class="soft-panel h-100">
                    <div class="fw-semibold mb-1"><?= h($proof['driver_name'] ?: 'Driver') ?></div>
                    <div class="small text-muted mb-3"><?= h((string)$proof['created_at']) ?></div>
                    <?php if (!empty($proof['photo_path'])): ?>
                      <div class="mb-3">
                        <div class="small text-muted mb-1">Photo</div>
                        <img src="../<?= h((string)$proof['photo_path']) ?>" alt="Delivery photo" class="img-fluid rounded border">
                      </div>
                    <?php endif; ?>
                    <?php if (!empty($proof['signature_path'])): ?>
                      <div class="mb-3">
                        <div class="small text-muted mb-1">Signature</div>
                        <img src="../<?= h((string)$proof['signature_path']) ?>" alt="Delivery signature" class="img-fluid rounded border bg-white">
                      </div>
                    <?php endif; ?>
                    <div class="small text-muted">Notes</div>
                    <div class="small"><?= h((string)($proof['notes'] ?? 'No notes')) ?></div>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </div>
</main>

<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>
<script>
const deliveryId = <?= (int)$deliveryId ?>;
const map = L.map('deliveryMap').setView([13.941, 121.615], 12);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  maxZoom: 19,
  attribution: '&copy; OpenStreetMap contributors'
}).addTo(map);

let pickupMarker = null;
let dropoffMarker = null;
let driverMarker = null;
let trailLine = null;
let firstFitDone = false;

function ensureMarker(existing, lat, lng, label) {
  if (lat === null || lng === null) return existing;
  const latlng = [Number(lat), Number(lng)];
  if (!existing) {
    existing = L.marker(latlng).addTo(map).bindPopup(label);
  } else {
    existing.setLatLng(latlng);
  }
  return existing;
}

async function fetchJson(url) {
  const response = await fetch(url, { headers: { 'Accept': 'application/json' } });
  const text = await response.text();
  try {
    return JSON.parse(text);
  } catch (error) {
    throw new Error(text.substring(0, 180) || 'Invalid JSON response');
  }
}

async function refreshMap() {
  try {
    const [latest, points] = await Promise.all([
      fetchJson(`location_latest.php?delivery_id=${encodeURIComponent(deliveryId)}`),
      fetchJson(`location_points.php?delivery_id=${encodeURIComponent(deliveryId)}&limit=120`),
    ]);

    if (latest.ok) {
      pickupMarker = ensureMarker(pickupMarker, latest.delivery.pickup_lat, latest.delivery.pickup_lng, 'Pickup');
      dropoffMarker = ensureMarker(dropoffMarker, latest.delivery.dropoff_lat, latest.delivery.dropoff_lng, 'Dropoff');
      if (latest.latest) {
        driverMarker = ensureMarker(driverMarker, latest.latest.lat, latest.latest.lng, 'Driver');
      }
    }

    if (points.ok && Array.isArray(points.points) && points.points.length > 1) {
      const trail = points.points.map((point) => [Number(point.lat), Number(point.lng)]);
      if (!trailLine) {
        trailLine = L.polyline(trail).addTo(map);
      } else {
        trailLine.setLatLngs(trail);
      }
    }

    if (!firstFitDone) {
      const bounds = [];
      if (pickupMarker) bounds.push(pickupMarker.getLatLng());
      if (dropoffMarker) bounds.push(dropoffMarker.getLatLng());
      if (driverMarker) bounds.push(driverMarker.getLatLng());
      if (bounds.length >= 2) {
        map.fitBounds(L.latLngBounds(bounds), { padding: [30, 30] });
        firstFitDone = true;
      } else if (bounds.length === 1) {
        map.setView(bounds[0], 15);
        firstFitDone = true;
      }
    }
  } catch (error) {
    console.error(error);
  }
}

refreshMap();
setInterval(refreshMap, 5000);
</script>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
