<?php
require_once '../_core.php';
is_logged_in();

$q      = trim($_GET['q'] ?? '');
$status = $_GET['status'] ?? '';

$where  = "WHERE 1=1";
$params = [];

if ($status === 'active' || $status === 'inactive') {
    $where .= " AND l.status = ?";
    $params[] = $status;
}
if ($q !== '') {
    $where .= " AND (l.name LIKE ? OR l.phone LIKE ?)";
    $params[] = "%$q%";
    $params[] = "%$q%";
}

try {
    $stmt = $pdo->prepare("
        SELECT l.*,
               p.name AS party_name,
               p.phone AS party_phone,
               (SELECT COUNT(*) FROM pawn_pledges pp WHERE pp.locker_id = l.id AND pp.status != 'CLOSED') AS pledge_count
        FROM lockers l
        LEFT JOIN parties p ON p.id = l.party_id
        $where
        ORDER BY l.created_at DESC
    ");
    $stmt->execute($params);
    echo json_encode(['success'=>true,'data'=>$stmt->fetchAll(PDO::FETCH_ASSOC)]);
} catch (Exception $e) {
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}