<?php
require_once __DIR__ . '/../../config/session.php';
require_once __DIR__ . '/../../config/db.php';
require_once __DIR__ . '/../../config/response.php';

if (!is_logged_in()) {
    send_response(401, false, 'লগইন প্রয়োজন', null);
}

$type   = $_GET['type'] ?? 'all';
$search = trim($_GET['search'] ?? '');
$limit  = (int)($_GET['limit'] ?? 50);
$offset = (int)($_GET['offset'] ?? 0);

if ($limit <= 0) $limit = 50;
if ($offset < 0) $offset = 0;

try {
    $where = "WHERE deleted_at IS NULL";
    $params = [];

    if ($type === 'customer') {
        $where .= " AND is_customer = 1";
    } elseif ($type === 'supplier') {
        $where .= " AND is_supplier = 1";
    } elseif ($type === 'pledge') {
        $where .= " AND is_pledge = 1";
    } elseif ($type === 'locker') {
        $where .= " AND is_locker = 1";
    } elseif ($type === 'karigar') {
        $where .= " AND is_karigar = 1";
    }

    if ($search !== '') {
        $where .= " AND (name LIKE ? OR phone LIKE ?)";
        $params[] = '%' . $search . '%';
        $params[] = '%' . $search . '%';
    }

    $countStmt = $pdo->prepare("SELECT COUNT(*) AS total FROM parties $where");
    $countStmt->execute($params);
    $total = (int)($countStmt->fetch(PDO::FETCH_ASSOC)['total'] ?? 0);

    $stmt = $pdo->prepare("
        SELECT id, name, phone, address, note,
               opening_receivable, opening_payable,
               balance, gold_balance,
               is_customer, is_supplier, is_pledge, is_locker, is_karigar,
               created_at
        FROM parties
        $where
        ORDER BY name ASC
        LIMIT ? OFFSET ?
    ");

    $dataParams = $params;
    $dataParams[] = $limit;
    $dataParams[] = $offset;
    $stmt->execute($dataParams);
    $parties = $stmt->fetchAll(PDO::FETCH_ASSOC);

    send_response(200, true, 'সফল', [
        'parties' => $parties,
        'total'   => $total,
        'limit'   => $limit,
        'offset'  => $offset
    ]);

} catch (Exception $e) {
    send_response(500, false, 'সার্ভার সমস্যা', ['error' => $e->getMessage()]);
}
