<?php
class MemberStatementController extends Controller
{
    public function show(Request $request): void
    {
        $memberId = (int)$request->routeParam('id');
        $db = $this->db();

        $member = $db->fetchOne(
            "SELECT m.id, m.membership_number, m.full_name_en, m.full_name_ar, m.primary_phone,
                    m.outstanding_balance, m.credit_balance, m.total_paid,
                    mt.name_en AS membership_type
             FROM members m
             LEFT JOIN membership_types mt ON m.membership_type_id=mt.id
             WHERE m.id=? AND m.is_deleted=0", [$memberId]
        );

        if (!$member) { $this->abort(404); return; }

        $dateFrom = $request->get('date_from', date('Y-01-01'));
        $dateTo   = $request->get('date_to', date('Y-m-d'));

        $ledger = $db->fetchAll(
            "SELECT ml.*, c.symbol AS currency_symbol
             FROM member_ledger ml
             LEFT JOIN sys_currencies c ON ml.currency_id=c.id
             WHERE ml.member_id=? AND ml.transaction_date BETWEEN ? AND ?
             ORDER BY ml.transaction_date, ml.id",
            [$memberId, $dateFrom, $dateTo]
        );

        $balance = $db->fetchOne("SELECT * FROM member_balances WHERE member_id=?", [$memberId]);

        $this->view('statement/index', [
            'title' => lang('finance.member_statement') . ' - ' . $member['full_name_en'],
            'breadcrumbs' => [
                ['label' => lang('finance.title'), 'url' => '/finance/invoices'],
                ['label' => lang('finance.member_statement')],
            ],
            'member'   => $member,
            'ledger'   => $ledger,
            'balance'  => $balance,
            'dateFrom' => $dateFrom,
            'dateTo'   => $dateTo,
        ]);
    }
}