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

$pdo = db();
$title = "Deliveries - IMS";
$user = current_user();

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

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

// Load drivers (users with role 'driver')
$drivers = $pdo->query("
  SELECT u.id, u.full_name, u.username
  FROM users u
  JOIN roles r ON r.id = u.role_id
  WHERE r.name = 'driver' AND u.is_active = 1
  ORDER BY u.full_name ASC
")->fetchAll();

// Load customers (optional)
$customers = $pdo->query("
  SELECT id, name
  FROM customers
  ORDER BY name ASC
")->fetchAll();

// ---------------------------
// Handle create delivery
// ---------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    $customer_id = post_int('customer_id') ?: null;
    $assigned_driver_id = post_int('assigned_driver_id') ?: null;

    $pickup_address = post_str('pickup_address');
    $dropoff_address = post_str('dropoff_address');
    $scheduled_at = post_str('scheduled_at'); // datetime-local string
    $notes = post_str('notes');

    // optional coordinates
    $pickup_lat = post_str('pickup_lat');
    $pickup_lng = post_str('pickup_lng');
    $dropoff_lat = post_str('dropoff_lat');
    $dropoff_lng = post_str('dropoff_lng');

    if ($pickup_address === '' || $dropoff_address === '') {
        $error = "Pickup and Dropoff address are required.";
    } else {
        // Generate code like: DLV-20260128-123456
        $delivery_code = 'DLV-' . date('Ymd') . '-' . random_int(100000, 999999);

        $status = $assigned_driver_id ? 'ASSIGNED' : 'PENDING';

        // Convert datetime-local to MySQL datetime (YYYY-MM-DD HH:MM:SS)
        $scheduled_mysql = null;
        if ($scheduled_at !== '') {
            $scheduled_mysql = str_replace('T', ' ', $scheduled_at) . ':00';
        }

        try {
            $stmt = $pdo->prepare("
              INSERT INTO deliveries
              (delivery_code, customer_id, assigned_driver_id, status,
               pickup_address, dropoff_address,
               pickup_lat, pickup_lng, dropoff_lat, dropoff_lng,
               notes, scheduled_at, created_by)
              VALUES
              (:delivery_code, :customer_id, :assigned_driver_id, :status,
               :pickup_address, :dropoff_address,
               :pickup_lat, :pickup_lng, :dropoff_lat, :dropoff_lng,
               :notes, :scheduled_at, :created_by)
            ");
            $stmt->execute([
                ':delivery_code' => $delivery_code,
                ':customer_id' => $customer_id,
                ':assigned_driver_id' => $assigned_driver_id,
                ':status' => $status,
                ':pickup_address' => $pickup_address,
                ':dropoff_address' => $dropoff_address,
                ':pickup_lat' => ($pickup_lat !== '' ? $pickup_lat : null),
                ':pickup_lng' => ($pickup_lng !== '' ? $pickup_lng : null),
                ':dropoff_lat' => ($dropoff_lat !== '' ? $dropoff_lat : null),
                ':dropoff_lng' => ($dropoff_lng !== '' ? $dropoff_lng : null),
                ':notes' => ($notes !== '' ? $notes : null),
                ':scheduled_at' => $scheduled_mysql,
                ':created_by' => $user['id'],
            ]);

            $success = "Delivery created successfully ($delivery_code).";
        } catch (PDOException $e) {
            $error = "Error creating delivery: " . $e->getMessage();
        }
    }
}

// ---------------------------
// Handle status update (quick action)
// ---------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'status') {
    $id = post_int('id');
    $status = post_str('status');

    $allowed = ['PENDING','ASSIGNED','PICKED_UP','IN_TRANSIT','DELIVERED','CANCELLED'];

    if ($id <= 0 || !in_array($status, $allowed, true)) {
        $error = "Invalid status update.";
    } else {
        try {
            $extraSql = "";
            if ($status === 'PICKED_UP') $extraSql = ", picked_up_at = NOW()";
            if ($status === 'DELIVERED') $extraSql = ", delivered_at = NOW()";

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

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

// ---------------------------
// Fetch deliveries list
// ---------------------------
$deliveries = $pdo->query("
  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
  ORDER BY d.created_at DESC
  LIMIT 200
")->fetchAll();

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">
    <h4 class="mb-0">Deliveries</h4>
  </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">
    <!-- Create Delivery -->
    <div class="col-12 col-lg-4">
      <div class="card shadow-sm">
        <div class="card-body">
          <h5 class="card-title mb-3">Create Delivery</h5>

          <form method="POST">
            <input type="hidden" name="action" value="create">

           <label class="form-label d-flex justify-content-between align-items-center">
  <span>Customer (optional)</span>
  <button type="button" class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#addCustomerModal">
    + Add Customer
  </button>
</label>

<select class="form-select" name="customer_id" id="customer_id">
  <option value="0">-- None --</option>
  <?php foreach ($customers as $c): ?>
    <option value="<?= (int)$c['id'] ?>"><?= htmlspecialchars($c['name']) ?></option>
  <?php endforeach; ?>
</select>

<div class="form-text">
  Selecting a customer can auto-fill the dropoff address.
</div>

            <div class="mb-2">
              <label class="form-label">Assign Driver (optional)</label>
              <select class="form-select" name="assigned_driver_id">
                <option value="0">-- Unassigned --</option>
                <?php foreach ($drivers as $d): ?>
                  <option value="<?= (int)$d['id'] ?>"><?= htmlspecialchars($d['full_name']) ?> (<?= htmlspecialchars($d['username']) ?>)</option>
                <?php endforeach; ?>
              </select>
              <div class="form-text">If assigned, status becomes <b>ASSIGNED</b>.</div>
            </div>

            <div class="mb-2">
              <label class="form-label">Pickup Address *</label>
              <textarea id="pickup_address" class="form-control" name="pickup_address" rows="2" required></textarea>
            </div>

            <div class="mb-2">
              <label class="form-label">Dropoff Address *</label>
              <textarea id="dropoff_address" class="form-control" name="dropoff_address" rows="2" required></textarea>
            </div>

            <div class="mb-2">
              <label class="form-label">Scheduled (optional)</label>
              <input class="form-control" type="datetime-local" name="scheduled_at">
            </div>

            <div class="row g-2">
              <div class="col-6">
                <label class="form-label small">Pickup Lat</label>
                <input id="pickup_lat" class="form-control form-control-sm" name="pickup_lat" placeholder="e.g. 14.5995">
              </div>
              <div class="col-6">
                <label class="form-label small">Pickup Lng</label>
                <input id="pickup_lng" class="form-control form-control-sm" name="pickup_lng" placeholder="e.g. 120.9842">
              </div>
              <div class="col-6">
                <label class="form-label small">Dropoff Lat</label>
                <input id="dropoff_lat" class="form-control form-control-sm" name="dropoff_lat">
              </div>
              <div class="col-6">
                <label class="form-label small">Dropoff Lng</label>
                <input id="dropoff_lng" class="form-control form-control-sm" name="dropoff_lng">
              </div>
              <div class="form-text">
                Coordinates optional (we’ll add a map picker later).
              </div>
            </div>

            <div class="mt-2 mb-3">
              <label class="form-label">Notes (optional)</label>
              <input class="form-control" name="notes" maxlength="255">
            </div>

            <hr class="my-3">

<div class="d-flex gap-2 mb-2">
  <button type="button" id="btnModePickup" class="btn btn-sm btn-outline-primary">Set Pickup</button>
  <button type="button" id="btnModeDropoff" class="btn btn-sm btn-outline-success">Set Dropoff</button>
  <div class="small text-muted align-self-center" id="mapModeText">Mode: Pickup</div>
</div>

<div id="pickerMap" style="height: 260px; width: 100%; border-radius: 8px;"></div>

<div class="form-text mt-2">
  Click on the map to set coordinates. Pickup = blue marker, Dropoff = green marker.
</div>


            <button class="btn btn-primary w-100" type="submit">Create</button>
          </form>
        </div>
      </div>
    </div>

    <!-- Delivery List -->
    <div class="col-12 col-lg-8">
      <div class="card shadow-sm">
        <div class="card-body">
          <h6 class="mb-3">Latest Deliveries</h6>

          <div class="table-responsive">
            <table class="table table-sm align-middle">
              <thead>
                <tr>
                  <th>Code</th>
                  <th>Customer</th>
                  <th>Driver</th>
                  <th>Status</th>
                  <th>Scheduled</th>
                  <th style="width:220px;"></th>
                </tr>
              </thead>
              <tbody>
              <?php if (!$deliveries): ?>
                <tr><td colspan="6" class="text-muted">No deliveries yet.</td></tr>
              <?php else: ?>
                <?php foreach ($deliveries as $dv): ?>
                  <tr>
                    <td class="fw-semibold"><?= htmlspecialchars($dv['delivery_code']) ?></td>
                    <td><?= htmlspecialchars($dv['customer_name'] ?? '-') ?></td>
                    <td><?= htmlspecialchars($dv['driver_name'] ?? '-') ?></td>
                    <td><span class="badge text-bg-secondary"><?= htmlspecialchars($dv['status']) ?></span></td>
                    <td><?= htmlspecialchars($dv['scheduled_at'] ?? '-') ?></td>
                    <td class="text-end">
                      <a class="btn btn-outline-primary btn-sm" href="delivery_view.php?id=<?= (int)$dv['id'] ?>">View</a>
                      <a class="btn btn-outline-dark btn-sm" href="map_live.php?id=<?= (int)$dv['id'] ?>">Map</a>


                      <form method="POST" class="d-inline">
                        <input type="hidden" name="action" value="status">
                        <input type="hidden" name="id" value="<?= (int)$dv['id'] ?>">
                        <select name="status" class="form-select form-select-sm d-inline-block" style="width:auto;">
                          <?php
                            $statuses = ['PENDING','ASSIGNED','PICKED_UP','IN_TRANSIT','DELIVERED','CANCELLED'];
                            foreach ($statuses as $st):
                              $sel = ($dv['status'] === $st) ? 'selected' : '';
                          ?>
                            <option value="<?= $st ?>" <?= $sel ?>><?= $st ?></option>
                          <?php endforeach; ?>
                        </select>
                        <button class="btn btn-sm btn-outline-success" type="submit">Update</button>
                      </form>
                    </td>
                  </tr>
                <?php endforeach; ?>
              <?php endif; ?>
              </tbody>
            </table>
          </div>

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

<link rel="stylesheet" href="https://unpkg.com/leaflet@1.9.4/dist/leaflet.css">
<script src="https://unpkg.com/leaflet@1.9.4/dist/leaflet.js"></script>

<script>
let mode = 'pickup'; // pickup | dropoff

const pickupLat = document.getElementById('pickup_lat');
const pickupLng = document.getElementById('pickup_lng');
const dropoffLat = document.getElementById('dropoff_lat');
const dropoffLng = document.getElementById('dropoff_lng');

const btnPickup = document.getElementById('btnModePickup');
const btnDropoff = document.getElementById('btnModeDropoff');
const modeText = document.getElementById('mapModeText');

function setMode(newMode) {
  mode = newMode;
  modeText.textContent = 'Mode: ' + (mode === 'pickup' ? 'Pickup' : 'Dropoff');

  btnPickup.classList.toggle('btn-primary', mode === 'pickup');
  btnPickup.classList.toggle('btn-outline-primary', mode !== 'pickup');

  btnDropoff.classList.toggle('btn-success', mode === 'dropoff');
  btnDropoff.classList.toggle('btn-outline-success', mode !== 'dropoff');
}

btnPickup.addEventListener('click', () => setMode('pickup'));
btnDropoff.addEventListener('click', () => setMode('dropoff'));

// Default location (Manila)
const defaultCenter = [14.5995, 120.9842];

const map = L.map('pickerMap').setView(defaultCenter, 13);
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;

function upsertMarker(existing, latlng, label) {
  if (!existing) {
    existing = L.marker(latlng).addTo(map).bindPopup(label);
  } else {
    existing.setLatLng(latlng);
  }
  return existing;
}

// If inputs already have values, place markers
function maybeInitMarkers() {
  const pLat = parseFloat(pickupLat.value);
  const pLng = parseFloat(pickupLng.value);
  const dLat = parseFloat(dropoffLat.value);
  const dLng = parseFloat(dropoffLng.value);

  const bounds = [];

  if (!isNaN(pLat) && !isNaN(pLng)) {
    pickupMarker = upsertMarker(pickupMarker, [pLat, pLng], 'Pickup');
    bounds.push([pLat, pLng]);
  }
  if (!isNaN(dLat) && !isNaN(dLng)) {
    dropoffMarker = upsertMarker(dropoffMarker, [dLat, dLng], 'Dropoff');
    bounds.push([dLat, dLng]);
  }

  if (bounds.length >= 2) {
    map.fitBounds(bounds, { padding: [20, 20] });
  } else if (bounds.length === 1) {
    map.setView(bounds[0], 15);
  }
}

maybeInitMarkers();

map.on('click', function(e) {
  const lat = e.latlng.lat;
  const lng = e.latlng.lng;

  if (mode === 'pickup') {
    pickupLat.value = lat.toFixed(7);
    pickupLng.value = lng.toFixed(7);
    pickupMarker = upsertMarker(pickupMarker, [lat, lng], 'Pickup');
  } else {
    dropoffLat.value = lat.toFixed(7);
    dropoffLng.value = lng.toFixed(7);
    dropoffMarker = upsertMarker(dropoffMarker, [lat, lng], 'Dropoff');
  }
});

// Start in pickup mode (visual)
setMode('pickup');
</script>

<!-- Add Customer Modal -->
<div class="modal fade" id="addCustomerModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title">Add Customer</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>

      <div class="modal-body">
        <div class="alert alert-danger d-none" id="custErr"></div>
        <div class="alert alert-success d-none" id="custOk"></div>

        <div class="mb-2">
          <label class="form-label">Name *</label>
          <input class="form-control" id="cust_name">
        </div>
        <div class="mb-2">
          <label class="form-label">Phone</label>
          <input class="form-control" id="cust_phone">
        </div>
        <div class="mb-2">
          <label class="form-label">Email</label>
          <input class="form-control" id="cust_email" type="email">
        </div>
        <div class="mb-2">
          <label class="form-label">Address</label>
          <textarea class="form-control" id="cust_address" rows="3"></textarea>
        </div>

        <div class="text-muted small">
          After saving, this customer will appear in the dropdown automatically.
        </div>
      </div>

      <div class="modal-footer">
        <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
        <button type="button" class="btn btn-primary" id="btnSaveCustomer">Save Customer</button>
      </div>
    </div>
  </div>
</div>

<script>
const customerSelect = document.getElementById('customer_id');
const dropoffTextarea = document.getElementById('dropoff_address');

async function fetchCustomer(id) {
  const res = await fetch(`../api/customer_get.php?id=${id}`);
  return await res.json();
}

customerSelect?.addEventListener('change', async () => {
  const id = customerSelect.value;
  if (!id || id === "0") return;

  try {
    const data = await fetchCustomer(id);
    if (!data.ok) return;

    // Auto-fill dropoff address if empty (or you can always overwrite if you want)
    const addr = (data.customer.address || '').trim();
    if (addr !== '' && dropoffTextarea.value.trim() === '') {
      dropoffTextarea.value = addr;
    }
  } catch (e) {}
});

// Modal save customer
const custErr = document.getElementById('custErr');
const custOk = document.getElementById('custOk');

function showErr(msg) {
  custOk.classList.add('d-none');
  custErr.textContent = msg;
  custErr.classList.remove('d-none');
}
function showOk(msg) {
  custErr.classList.add('d-none');
  custOk.textContent = msg;
  custOk.classList.remove('d-none');
}

document.getElementById('btnSaveCustomer')?.addEventListener('click', async () => {
  const payload = {
    name: document.getElementById('cust_name').value.trim(),
    phone: document.getElementById('cust_phone').value.trim(),
    email: document.getElementById('cust_email').value.trim(),
    address: document.getElementById('cust_address').value.trim(),
  };

  if (!payload.name) {
    showErr("Name is required.");
    return;
  }

  try {
    const res = await fetch('../api/customer_create.php', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify(payload)
    });
    const data = await res.json();

    if (!data.ok) {
      showErr(data.error || 'Failed to save customer.');
      return;
    }

    // Add new customer to dropdown and select it
    const opt = document.createElement('option');
    opt.value = data.customer.id;
    opt.textContent = data.customer.name;
    customerSelect.appendChild(opt);
    customerSelect.value = String(data.customer.id);

    // Auto-fill dropoff if empty
    if (payload.address && dropoffTextarea.value.trim() === '') {
      dropoffTextarea.value = payload.address;
    }

    showOk("Customer saved.");

  } catch (e) {
    showErr("Network error: " + e.message);
  }
});
</script>



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