<?php
/**
 * api/parties/search_party.php
 * GET ?q=মাধব&type=pledge  (type optional)
 * Partial Bengali match — name, phone, note সব দিয়ে search
 */
require_once __DIR__ . '/../../config/db.php';
header('Content-Type: application/json; charset=utf-8');

if (session_status() === PHP_SESSION_NONE) session_start();

$q    = trim($_GET['q']    ?? '');
$type = trim($_GET['type'] ?? ''); // pledge, customer, supplier, karigar, locker
$limit = min((int)($_GET['limit'] ?? 15), 30);

if (mb_strlen($q) < 1) {
    echo json_encode(['success' => true, 'parties' => []]);
    exit;
}

// Base query — deleted_at IS NULL সবসময়
$sql = "SELECT id, name, phone, address, is_customer, is_supplier, is_pledge, is_karigar, is_locker
        FROM parties
        WHERE deleted_at IS NULL
        AND (
            name  LIKE :q1
            OR phone LIKE :q2
            OR note  LIKE :q3
        )";

// Type filter
switch ($type) {
    case 'pledge':   $sql .= " AND is_pledge=1";   break;
    case 'customer': $sql .= " AND is_customer=1"; break;
    case 'supplier': $sql .= " AND is_supplier=1"; break;
    case 'karigar':  $sql .= " AND is_karigar=1";  break;
    case 'locker':   $sql .= " AND is_locker=1";   break;
    // type না দিলে সব আসবে
}

$sql .= " ORDER BY name ASC LIMIT :lim";

$like = '%' . $q . '%';

$s = $pdo->prepare($sql);
$s->bindValue(':q1',  $like,   PDO::PARAM_STR);
$s->bindValue(':q2',  $like,   PDO::PARAM_STR);
$s->bindValue(':q3',  $like,   PDO::PARAM_STR);
$s->bindValue(':lim', $limit,  PDO::PARAM_INT);
$s->execute();
$rows = $s->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([
    'success' => true,
    'count'   => count($rows),
    'parties' => array_map(function($r) {
        return [
            'id'      => (int)$r['id'],
            'name'    => $r['name'],
            'phone'   => $r['phone'] ?? '',
            'address' => $r['address'] ?? '',
            'tags'    => array_filter([
                $r['is_pledge']   ? 'বন্ধক'     : null,
                $r['is_customer'] ? 'গ্রাহক'    : null,
                $r['is_supplier'] ? 'সরবরাহকারী': null,
                $r['is_karigar']  ? 'কারিগর'    : null,
                $r['is_locker']   ? 'লকার'      : null,
            ]),
        ];
    }, $rows),
]);