<?php
// app/models/LaundryBagEvent.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/Notification.php';

class LaundryBagEvent
{
  public static function add(
    int $bagId,
    string $itemType,
    string $action,
    string $statusAfter,
    ?int $userId = null,
    ?string $note = null,
    ?float $geoLat = null,
    ?float $geoLng = null,
    ?int $geoAccuracy = null,
    ?string $geoAddress = null
  ): void {
    $stmt = db()->prepare("
      INSERT INTO laundry_bag_events
        (bag_id, item_type, action, status_after, note, changed_by_user_id,
         geo_lat, geo_lng, geo_accuracy, geo_address, created_at)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())
    ");
    $stmt->execute([
      $bagId, $itemType, $action, $statusAfter, $note, $userId,
      $geoLat, $geoLng, $geoAccuracy, $geoAddress
    ]);

    // Notify admins when delivered
    if ($action === 'delivered') {
      try {
        $q = db()->prepare("
          SELECT b.bag_number, un.unit_code, bl.name AS building_name
          FROM laundry_bags b
          JOIN units un ON un.id = b.unit_id
          JOIN buildings bl ON bl.id = un.building_id
          WHERE b.id = ?
          LIMIT 1
        ");
        $q->execute([$bagId]);
        $r = $q->fetch();

        $bagNumber = $r['bag_number'] ?? ('Bag #' . $bagId);
        $unitCode  = $r['unit_code'] ?? '';
        $building  = $r['building_name'] ?? '';

        $locLine = '';
        if (!empty($geoAddress)) {
          $locLine = " Location: " . $geoAddress . ".";
        } elseif ($geoLat !== null && $geoLng !== null) {
          $locLine = " Location: {$geoLat}, {$geoLng}" . ($geoAccuracy ? " (±{$geoAccuracy}m)" : "") . ".";
        }

        Notification::notifyAdmins(
          'laundry_delivered',
          'Laundry delivered',
          "{$building} • {$unitCode} • Bag {$bagNumber} — {$itemType} delivered." . $locLine,
          "/laundry_bag.php?bag_id=" . (int)$bagId,
          $userId
        );
      } catch (Throwable $e) {}
    }
  }

  public static function listForBag(int $bagId, int $limit = 200): array
  {
    $limit = max(1, min($limit, 1000));
    $stmt = db()->prepare("
      SELECT e.*, u.full_name AS staff_name
      FROM laundry_bag_events e
      LEFT JOIN users u ON u.id = e.changed_by_user_id
      WHERE e.bag_id = ?
      ORDER BY e.created_at DESC, e.id DESC
      LIMIT {$limit}
    ");
    $stmt->execute([$bagId]);
    return $stmt->fetchAll();
  }

  public static function listAll(int $limit = 300): array
  {
    $limit = max(1, min($limit, 2000));
    $stmt = db()->query("
      SELECT e.*,
             u.full_name AS staff_name,
             b.unit_id,
             b.bag_number,
             un.unit_code,
             bl.name AS building_name
      FROM laundry_bag_events e
      JOIN laundry_bags b ON b.id = e.bag_id
      JOIN units un ON un.id = b.unit_id
      JOIN buildings bl ON bl.id = un.building_id
      LEFT JOIN users u ON u.id = e.changed_by_user_id
      ORDER BY e.created_at DESC, e.id DESC
      LIMIT {$limit}
    ");
    return $stmt->fetchAll();
  }

  /**
   * ✅ FIX for laundry_today.php
   * Returns events between date range, optionally filtered by building name.
   * $building expects exact building name (matches LaundryBag::listBuildingsWithBags()).
   */
  public static function listByDateRange(
    string $startDateTime,
    string $endDateTime,
    ?string $building = null,
    int $limit = 5000
  ): array {
    $limit = max(1, min($limit, 10000));
    $building = trim((string)$building);
    if ($building === '') $building = null;

    $where = ["e.created_at >= ?", "e.created_at < ?"];
    $params = [$startDateTime, $endDateTime];

    if ($building !== null) {
      $where[] = "bl.name = ?";
      $params[] = $building;
    }

    $sql = "
      SELECT e.*,
             u.full_name AS staff_name,
             b.unit_id,
             b.bag_number,
             un.unit_code,
             bl.name AS building_name
      FROM laundry_bag_events e
      JOIN laundry_bags b ON b.id = e.bag_id
      JOIN units un ON un.id = b.unit_id
      JOIN buildings bl ON bl.id = un.building_id
      LEFT JOIN users u ON u.id = e.changed_by_user_id
      WHERE " . implode(" AND ", $where) . "
      ORDER BY e.created_at DESC, e.id DESC
      LIMIT {$limit}
    ";

    $stmt = db()->prepare($sql);
    $stmt->execute($params);
    return $stmt->fetchAll();
  }
}
