<?php

class AdvFinanceApiController extends Controller
{
    public function memberSearch(Request $request): void
    {
        $q = trim($request->get('q', ''));
        if (mb_strlen($q) < 2) {
            $this->json(['results' => [], 'pagination' => ['more' => false]]);
            return;
        }
        $db = $this->db();
        $like = "%{$q}%";
        $rows = $db->fetchAll(
            "SELECT id, membership_number, full_name_en, full_name_ar, primary_phone
             FROM members
             WHERE is_deleted = 0
               AND (membership_number LIKE ? OR full_name_en LIKE ? OR full_name_ar LIKE ? OR national_id LIKE ? OR primary_phone LIKE ?)
             ORDER BY full_name_en
             LIMIT 30",
            [$like, $like, $like, $like, $like]
        );
        $results = [];
        foreach ($rows as $r) {
            $results[] = [
                'id'   => $r['id'],
                'text'  => $r['membership_number'] . ' — ' . ($r['full_name_en'] ?: $r['full_name_ar']),
            ];
        }
        $this->json(['results' => $results, 'pagination' => ['more' => false]]);
    }

    public function invoiceSearch(Request $request): void
    {
        $memberId = (int)$request->get('member_id', 0);
        $q = trim($request->get('q', ''));
        $db = $this->db();
        $params = [];
        $where = "i.is_deleted = 0 AND i.status IN ('issued','partially_paid','overdue')";
        if ($memberId) {
            $where .= " AND i.member_id = ?";
            $params[] = $memberId;
        }
        if ($q) {
            $where .= " AND (i.invoice_number LIKE ?)";
            $params[] = "%{$q}%";
        }
        $rows = $db->fetchAll(
            "SELECT i.id, i.invoice_number, i.total_amount, i.balance_due, i.invoice_type,
                    m.membership_number, m.full_name_en
             FROM invoices i
             JOIN members m ON i.member_id = m.id
             WHERE {$where}
             ORDER BY i.invoice_date DESC
             LIMIT 30",
            $params
        );
        $results = [];
        foreach ($rows as $r) {
            $results[] = [
                'id'   => $r['id'],
                'text'  => $r['invoice_number'] . ' — ' . money($r['balance_due']) . ' due',
                'balance_due' => $r['balance_due'],
                'total_amount' => $r['total_amount'],
            ];
        }
        $this->json(['results' => $results, 'pagination' => ['more' => false]]);
    }
}