<?php
// public/delivery_view.php
require_once __DIR__ . '/../helpers/auth.php';
require_once __DIR__ . '/../helpers/audit.php';


require_role(['admin', 'staff']);

$pdo = db();
$title = "Delivery View - IMS";

function get_int(string $k): int { return (int)($_GET[$k] ?? 0); }
function post_int(string $k): int { return (int)($_POST[$k] ?? 0); }
function post_str(string $k): string { return trim((string)($_POST[$k] ?? '')); }

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

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

// ---------------------------
// Load delivery (function so we can reload after POST)
// ---------------------------
function load_delivery(PDO $pdo, int $delivery_id): array {
    $deliveryStmt = $pdo->prepare("
      SELECT
        d.*,
        c.name AS customer_name,
        u.full_name AS driver_name
      FROM deliveries d
      LEFT JOIN customers c ON c.id = d.customer_id
      LEFT JOIN users u ON u.id = d.assigned_driver_id
      WHERE d.id = :id
      LIMIT 1
    ");
    $deliveryStmt->execute([':id' => $delivery_id]);
    $delivery = $deliveryStmt->fetch(PDO::FETCH_ASSOC);
    return $delivery ?: [];
}

$delivery = load_delivery($pdo, $delivery_id);
if (!$delivery) {
    http_response_code(404);
    die("Delivery not found.");
}

// Load products for add-item dropdown
$products = $pdo->query("
  SELECT id, sku, name
  FROM products
  WHERE is_active = 1
  ORDER BY name ASC
")->fetchAll(PDO::FETCH_ASSOC);

// ---------------------------
// Actions: add_item, delete_item, update_status
// ---------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    // Add item (no UNIQUE index needed)
    if ($action === 'add_item') {
        $product_id = post_int('product_id');
        $qty = post_int('quantity');

        if ($product_id <= 0 || $qty <= 0) {
            $error = "Select a product and quantity > 0.";
        } else {
            try {
                // If already exists -> update qty, else insert
                $chk = $pdo->prepare("
                  SELECT id, quantity
                  FROM delivery_items
                  WHERE delivery_id = :did AND product_id = :pid
                  LIMIT 1
                ");
                $chk->execute([':did' => $delivery_id, ':pid' => $product_id]);
                $row = $chk->fetch(PDO::FETCH_ASSOC);

                if ($row) {
                    $upd = $pdo->prepare("
                      UPDATE delivery_items
                      SET quantity = quantity + :qty
                      WHERE id = :id
                      LIMIT 1
                    ");
                    $upd->execute([':qty' => $qty, ':id' => (int)$row['id']]);
                } else {
                    $ins = $pdo->prepare("
                      INSERT INTO delivery_items (delivery_id, product_id, quantity)
                      VALUES (:did, :pid, :qty)
                    ");
                    $ins->execute([':did' => $delivery_id, ':pid' => $product_id, ':qty' => $qty]);
                }

                $success = "Item added to delivery.";
            } catch (PDOException $e) {
                $error = "Error adding item: " . $e->getMessage();
            }
        }
    }

    // Remove item
    if ($action === 'delete_item') {
        $item_id = post_int('item_id');
        if ($item_id <= 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' => $item_id, ':delivery_id' => $delivery_id]);
                $success = "Item removed.";
            } catch (PDOException $e) {
                $error = "Error removing item: " . $e->getMessage();
            }
        }
    }

    // Update status
    if ($action === 'update_status') {
        $new_status = post_str('status');
        $allowed = ['PENDING','ASSIGNED','PICKED_UP','IN_TRANSIT','DELIVERED','CANCELLED'];

        if (!in_array($new_status, $allowed, true)) {
            $error = "Invalid status.";
        } else {
            try {
                // Update delivery status + timestamps
                $extraSql = "";
                if ($new_status === 'PICKED_UP') $extraSql = ", picked_up_at = NOW()";
                if ($new_status === 'DELIVERED') $extraSql = ", delivered_at = NOW()";

                $stmt = $pdo->prepare("UPDATE deliveries SET status = :st $extraSql WHERE id = :id LIMIT 1");
                $stmt->execute([':st' => $new_status, ':id' => $delivery_id]);

                // If delivered: deduct inventory OUT (only once)
                if ($new_status === 'DELIVERED') {
                    // Check if already deducted
                    $chk = $pdo->prepare("
                      SELECT COUNT(*) AS cnt
                      FROM inventory_movements
                      WHERE reference_type='DELIVERY' AND reference_id = :rid AND movement_type='OUT'
                    ");
                    $chk->execute([':rid' => $delivery_id]);
                    $already = (int)($chk->fetch(PDO::FETCH_ASSOC)['cnt'] ?? 0);

                    if ($already === 0) {
                        // Get delivery items
                        $itemsStmt = $pdo->prepare("
                          SELECT di.product_id, di.quantity, p.name
                          FROM delivery_items di
                          JOIN products p ON p.id = di.product_id
                          WHERE di.delivery_id = :did
                        ");
                        $itemsStmt->execute([':did' => $delivery_id]);
                        $rows = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);

                        if (!$rows) {
                            $error = "Delivery marked DELIVERED, but no items found (no stock deducted).";
                        } else {
                            // Check stock availability
                            foreach ($rows as $it) {
                                $pid = (int)$it['product_id'];
                                $need = (int)$it['quantity'];

                                $stockStmt = $pdo->prepare("
                                  SELECT
                                    COALESCE(SUM(CASE WHEN movement_type='IN' THEN quantity ELSE 0 END),0) -
                                    COALESCE(SUM(CASE WHEN movement_type='OUT' THEN quantity ELSE 0 END),0) +
                                    COALESCE(SUM(CASE WHEN movement_type='ADJUST' THEN quantity ELSE 0 END),0) AS stock
                                  FROM inventory_movements
                                  WHERE product_id = :pid
                                ");
                                $stockStmt->execute([':pid' => $pid]);
                                $stock = (int)($stockStmt->fetch(PDO::FETCH_ASSOC)['stock'] ?? 0);

                                if ($need > $stock) {
                                    $error = "Not enough stock to deliver: " . $it['name'] . " (need $need, have $stock).";
                                    break;
                                }
                            }

                            // Deduct stock if ok
                            if ($error === '') {
                                $pdo->beginTransaction();
                                try {
                                    foreach ($rows as $it) {
                                        $ins = $pdo->prepare("
                                          INSERT INTO inventory_movements
                                          (product_id, movement_type, quantity, unit_cost, reference_type, reference_id, notes, created_by)
                                          VALUES
                                          (:pid, 'OUT', :qty, NULL, 'DELIVERY', :rid, :notes, :uid)
                                        ");
                                        $ins->execute([
                                            ':pid' => (int)$it['product_id'],
                                            ':qty' => (int)$it['quantity'],
                                            ':rid' => $delivery_id,
                                            ':notes' => 'Delivered via ' . ($delivery['delivery_code'] ?? ''),
                                            ':uid' => (int)($delivery['created_by'] ?? 0),
                                        ]);
                                    }
                                    $pdo->commit();
                                    $success = "Status updated + stock deducted (DELIVERED).";
                                    audit_log(
                                 'DRIVER_UPDATE_STATUS',
                                 'deliveries',
                                           (string)$delivery_id,
                                 'Driver set status to ' . $new_status  
                                            );

                                } catch (Throwable $t) {
                                    $pdo->rollBack();
                                    $error = "Delivery set to DELIVERED but stock deduction failed: " . $t->getMessage();
                                }
                            }
                        }
                    } else {
                        $success = "Status updated to DELIVERED (stock already deducted).";
                    }
                } else {
                    $success = "Status updated to $new_status.";
                }

            } catch (PDOException $e) {
                $error = "Error updating status: " . $e->getMessage();
            }
        }
    }

    // reload delivery after actions
    $delivery = load_delivery($pdo, $delivery_id);
}

// Load delivery items
$itemsStmt = $pdo->prepare("
  SELECT di.id, di.quantity, p.sku, p.name
  FROM delivery_items di
  JOIN products p ON p.id = di.product_id
  WHERE di.delivery_id = :did
  ORDER BY di.id DESC
");
$itemsStmt->execute([':did' => $delivery_id]);
$items = $itemsStmt->fetchAll(PDO::FETCH_ASSOC);

// Check whether stock already deducted for this delivery
$deductedStmt = $pdo->prepare("
  SELECT COUNT(*) AS cnt
  FROM inventory_movements
  WHERE reference_type='DELIVERY' AND reference_id = :rid AND movement_type='OUT'
");
$deductedStmt->execute([':rid' => $delivery_id]);
$already_deducted = (int)($deductedStmt->fetch(PDO::FETCH_ASSOC)['cnt'] ?? 0);

// Load POD proofs (admin/staff view)
$podsStmt = $pdo->prepare("
  SELECT dp.*, 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
");
$podsStmt->execute([':did' => $delivery_id]);
$pods = $podsStmt->fetchAll(PDO::FETCH_ASSOC);

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

<main class="col-12 col-md-9 col-lg-10 p-3 p-md-4">
  <div class="d-flex align-items-center justify-content-between mb-3">
    <div>
      <h4 class="mb-0">Delivery: <?= htmlspecialchars($delivery['delivery_code'] ?? '-') ?></h4>
      <div class="text-muted small">Created: <?= htmlspecialchars($delivery['created_at'] ?? '-') ?></div>
    </div>
    <a class="btn btn-outline-secondary btn-sm" href="deliveries.php">Back</a>
  </div>

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

  <?php if ($success !== ''): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
  <?php endif; ?>

  <div class="row g-3">
    <!-- Details -->
    <div class="col-12 col-lg-5">
      <div class="card shadow-sm">
        <div class="card-body">
          <h6 class="mb-3">Details</h6>

          <div class="mb-2"><b>Customer:</b> <?= htmlspecialchars($delivery['customer_name'] ?? '-') ?></div>
          <div class="mb-2"><b>Driver:</b> <?= htmlspecialchars($delivery['driver_name'] ?? '-') ?></div>
          <div class="mb-2"><b>Status:</b> <span class="badge text-bg-secondary"><?= htmlspecialchars($delivery['status'] ?? '-') ?></span></div>

          <div class="mb-2"><b>Scheduled:</b> <?= htmlspecialchars($delivery['scheduled_at'] ?? '-') ?></div>
          <div class="mb-2"><b>Picked up:</b> <?= htmlspecialchars($delivery['picked_up_at'] ?? '-') ?></div>
          <div class="mb-2"><b>Delivered:</b> <?= htmlspecialchars($delivery['delivered_at'] ?? '-') ?></div>

          <hr>

          <div class="mb-2"><b>Pickup:</b><br><?= nl2br(htmlspecialchars($delivery['pickup_address'] ?? '')) ?></div>
          <div class="mb-2"><b>Dropoff:</b><br><?= nl2br(htmlspecialchars($delivery['dropoff_address'] ?? '')) ?></div>

          <div class="mb-2"><b>Notes:</b> <?= htmlspecialchars($delivery['notes'] ?? '-') ?></div>

          <hr>

          <form method="POST" class="d-flex gap-2">
            <input type="hidden" name="action" value="update_status">
            <select name="status" class="form-select">
              <?php
                $statuses = ['PENDING','ASSIGNED','PICKED_UP','IN_TRANSIT','DELIVERED','CANCELLED'];
                foreach ($statuses as $st):
                  $sel = (($delivery['status'] ?? '') === $st) ? 'selected' : '';
              ?>
                <option value="<?= $st ?>" <?= $sel ?>><?= $st ?></option>
              <?php endforeach; ?>
            </select>
            <button class="btn btn-outline-success" type="submit">Update</button>
          </form>

          <div class="small text-muted mt-2">
            If set to <b>DELIVERED</b>, stock will be deducted once.
            Current deduction state: <?= $already_deducted > 0 ? '✅ Deducted' : '❌ Not deducted' ?>
          </div>
        </div>
      </div>
    </div>

    <!-- Items -->
    <div class="col-12 col-lg-7">
      <div class="card shadow-sm mb-3">
        <div class="card-body">
          <h6 class="mb-3">Add Item</h6>

          <form method="POST" class="row g-2 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 --</option>
                <?php foreach ($products as $p): ?>
                  <option value="<?= (int)$p['id'] ?>">
                    <?= htmlspecialchars($p['name']) ?> (<?= htmlspecialchars($p['sku']) ?>)
                  </option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="col-12 col-md-4">
              <label class="form-label">Qty</label>
              <input class="form-control" name="quantity" type="number" min="1" step="1" required>
            </div>

            <div class="col-12">
              <button class="btn btn-primary w-100" type="submit">Add to Delivery</button>
            </div>
          </form>
        </div>
      </div>

      <div class="card shadow-sm">
        <div class="card-body">
          <h6 class="mb-3">Delivery Items</h6>

          <div class="table-responsive">
            <table class="table table-sm align-middle">
              <thead>
                <tr>
                  <th>SKU</th>
                  <th>Product</th>
                  <th class="text-end">Qty</th>
                  <th style="width:120px;"></th>
                </tr>
              </thead>
              <tbody>
                <?php if (!$items): ?>
                  <tr><td colspan="4" class="text-muted">No items yet.</td></tr>
                <?php else: ?>
                  <?php foreach ($items as $it): ?>
                    <tr>
                      <td><?= htmlspecialchars($it['sku']) ?></td>
                      <td><?= htmlspecialchars($it['name']) ?></td>
                      <td class="text-end fw-semibold"><?= (int)$it['quantity'] ?></td>
                      <td class="text-end">
                        <form method="POST" class="d-inline" onsubmit="return confirm('Remove this item?');">
                          <input type="hidden" name="action" value="delete_item">
                          <input type="hidden" name="item_id" value="<?= (int)$it['id'] ?>">
                          <button class="btn btn-outline-danger btn-sm" type="submit">Remove</button>
                        </form>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

          <div class="text-muted small">
            Delivery items are what the driver will see in the Driver App.
          </div>
        </div>
      </div>

      <!-- POD Viewer -->
      <div class="card shadow-sm mt-3">
        <div class="card-body">
          <h6 class="mb-3">Proof of Delivery (POD)</h6>

          <?php if (!$pods): ?>
            <div class="text-muted">No proof submitted yet.</div>
          <?php else: ?>
            <?php foreach ($pods as $p): ?>
              <div class="border rounded p-2 mb-3 bg-white">
                <div class="small text-muted">
                  Submitted by <b><?= htmlspecialchars($p['driver_name'] ?? '-') ?></b>
                  — <?= htmlspecialchars($p['created_at'] ?? '-') ?>
                </div>

                <?php if (!empty($p['photo_path'])): ?>
                  <div class="mt-2">
                    <img src="../<?= htmlspecialchars($p['photo_path']) ?>" class="img-fluid rounded">
                  </div>
                <?php endif; ?>

                <?php if (!empty($p['signature_path'])): ?>
                  <div class="mt-2">
                    <img src="../<?= htmlspecialchars($p['signature_path']) ?>" class="img-fluid rounded" style="max-height:180px;">
                  </div>
                <?php endif; ?>

                <?php if (!empty($p['notes'])): ?>
                  <div class="mt-2"><b>Notes:</b> <?= nl2br(htmlspecialchars($p['notes'])) ?></div>
                <?php endif; ?>
              </div>
            <?php endforeach; ?>
          <?php endif; ?>
        </div>
      </div>

    </div>
  </div>
</main>

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