<?php
require_once __DIR__ . '/../include/db.php';
session_start();
if (!isset($_SESSION['delivery_man_id'])) {
    header("Location: delivery_login.php");
    exit;
}
$delivery_man_id = intval($_SESSION['delivery_man_id']);

// Query aggregated per order for this delivery man
$stmt = $conn->prepare("
    SELECT 
        o.id AS order_id,
        o.buyer_name,
        o.style_no,
        o.po_no,
        DATE(o.created_at) AS order_date,
        IFNULL(SUM(a.assigned_qty),0) AS total_assigned_qty,
        IFNULL(SUM(a.delivered_qty),0) AS total_delivered,
        CASE 
            WHEN IFNULL(SUM(a.delivered_qty),0) >= IFNULL(SUM(a.assigned_qty),0) 
                 AND IFNULL(SUM(a.assigned_qty),0) > 0 
            THEN 'delivered'
            WHEN IFNULL(SUM(a.delivered_qty),0) > 0 
            THEN 'partial'
            ELSE 'pending'
        END AS order_status
    FROM delivery_assignments a
    JOIN orders o ON a.order_id = o.id
    WHERE a.delivery_man_id = ?
    GROUP BY o.id
    HAVING total_delivered < total_assigned_qty
    ORDER BY o.created_at DESC
");

$stmt->bind_param("i", $delivery_man_id);
$stmt->execute();
$res = $stmt->get_result();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Delivery Dashboard</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
<style>
@media (max-width: 576px) {
  h4 {
    font-size: 16px;
  }
  table th, table td {
    font-size: 12px;
    padding: 6px;
    white-space: nowrap;
  }
  .btn-sm {
    font-size: 11px;
    padding: 4px 6px;
  }
}
</style>

</head>
<body class="bg-light">
<nav class="navbar navbar-dark bg-primary">
  <div class="container">
    <span class="navbar-brand">Welcome, <?= htmlspecialchars($_SESSION['delivery_man_name'] ?? 'Delivery') ?></span>
    <a href="logout.php" class="btn btn-light btn-sm">Logout</a>
  </div>
</nav>

<div class="container mt-4">
  <h4>Your Assigned Orders</h4>
<div class="card mt-3 p-2">
  <div class="table-responsive">
    <table class="table table-bordered table-sm align-middle">
      <thead class="table-dark"><tr><th>Buyer</th><th>Style</th><th>Po</th><th>Assigned Qty</th><th>Delivered</th><th>Status</th><th>Action</th></tr></thead>
      <tbody>
      <?php while($o = $res->fetch_assoc()): ?>
        <tr>
          <td><?= htmlspecialchars($o['buyer_name']) ?></td>
          <td><?= htmlspecialchars($o['style_no']) ?></td>
          <td><?= htmlspecialchars($o['po_no']) ?></td>
          
          <td><?= intval($o['total_assigned_qty']) ?></td>
          <td><?= intval($o['total_delivered']) ?></td>
          <td><?= ucfirst(htmlspecialchars($o['order_status'])) ?></td>
          <td>
            <button class="btn btn-primary btn-sm orderUpdateBtn" data-order_id="<?= intval($o['order_id']) ?>">Update Delivery</button>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
  </div>
</div>


<!-- Modal -->
<div class="modal fade" id="orderUpdateModal" tabindex="-1">
  <div class="modal-dialog modal-lg">
    <form class="modal-content" method="post" action="update_delivery.php" enctype="multipart/form-data" id="updateForm">
      <div class="modal-header bg-primary text-white">
        <h5 class="modal-title">Submit Delivery</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" name="order_id" id="modal_order_id">
        <div id="assignments_container"></div>

        <div class="mb-2">
          <label class="form-label fw-bold">Challan Number</label>
          <input type="text" name="challan_number" class="form-control" required>
        </div>
        <div class="mb-2">
          <label class="form-label fw-bold">Challan Image</label>
          <input type="file" name="challan_image" accept="image/*" class="form-control" required>
        </div>
        <div class="mb-2">
          <label class="form-label fw-bold">Remarks</label>
          <textarea name="remarks" class="form-control" rows="2"></textarea>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-success">Submit</button>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </form>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// fetch assignments summary and show modal
document.querySelectorAll('.orderUpdateBtn').forEach(btn => {
    btn.addEventListener('click', function(){
        const order_id = this.dataset.order_id;
        document.getElementById('modal_order_id').value = order_id;
        fetch('fetch_assignments.php?order_id=' + order_id)
            .then(res => res.text())
            .then(html => {
                document.getElementById('assignments_container').innerHTML = html;
                const modal = new bootstrap.Modal(document.getElementById('orderUpdateModal'));
                modal.show();
            });
    });
});
</script>
</body>
</html>
