<?php
class ReceiptController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('receipts/index', [
            'title' => lang('finance.receipts'),
            'breadcrumbs' => [
                ['label' => lang('finance.title'), 'url' => '/finance/invoices'],
                ['label' => lang('finance.receipts')],
            ],
        ]);
    }

    public function datatable(Request $request): void
    {
        $db = $this->db();
        $draw   = (int)$request->get('draw', 1);
        $start  = (int)$request->get('start', 0);
        $length = (int)$request->get('length', 25);
        $search = $request->get('search')['value'] ?? '';

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

        if ($search) {
            $where .= " AND (r.receipt_number LIKE ? OR m.full_name_en LIKE ? OR m.membership_number LIKE ?)";
            $s = "%{$search}%";
            $params = array_merge($params, [$s, $s, $s]);
        }

        $totalRecords = (int)$db->fetchColumn("SELECT COUNT(*) FROM receipts");
        $filteredCount = (int)$db->fetchColumn(
            "SELECT COUNT(*) FROM receipts r LEFT JOIN members m ON r.member_id=m.id WHERE {$where}", $params
        );

        $rows = $db->fetchAll(
            "SELECT r.id, r.receipt_number, r.receipt_date, r.total_amount, r.status,
                    m.full_name_en AS member_name, m.membership_number
             FROM receipts r
             LEFT JOIN members m ON r.member_id=m.id
             WHERE {$where}
             ORDER BY r.id DESC
             LIMIT {$length} OFFSET {$start}",
            $params
        );

        $data = [];
        foreach ($rows as $row) {
            $actions = '<div class="btn-group btn-group-sm">';
            $actions .= '<a href="/finance/receipts/'.$row['id'].'" class="btn btn-outline-primary"><i class="fas fa-eye"></i></a>';
            if (Gate::can('receipts.print')) {
                $actions .= '<a href="/finance/receipts/'.$row['id'].'/print" target="_blank" class="btn btn-outline-info"><i class="fas fa-print"></i></a>';
            }
            $actions .= '</div>';

            $data[] = [
                'id'             => $row['id'],
                'receipt_number' => e($row['receipt_number']),
                'member_name'    => e($row['member_name'] ?? ''),
                'total_amount'   => money($row['total_amount']),
                'receipt_date'   => format_date($row['receipt_date']),
                'status'         => status_badge($row['status']),
                'actions'        => $actions,
            ];
        }

        $this->json([
            'draw'            => $draw,
            'recordsTotal'    => $totalRecords,
            'recordsFiltered' => $filteredCount,
            'data'            => $data,
        ]);
    }

    public function show(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        $db = $this->db();

        $receipt = $db->fetchOne(
            "SELECT r.*, m.full_name_en AS member_name, m.membership_number,
                    pm.name_en AS method_name, c.symbol AS currency_symbol, c.currency_code
             FROM receipts r
             LEFT JOIN members m ON r.member_id=m.id
             LEFT JOIN payment_methods pm ON r.payment_method_id=pm.id
             LEFT JOIN sys_currencies c ON r.currency_id=c.id
             WHERE r.id=?", [$id]
        );

        if (!$receipt) {
            $this->abort(404, 'Receipt not found');
            return;
        }

        $items = $db->fetchAll("SELECT * FROM receipt_items WHERE receipt_id=? ORDER BY sort_order", [$id]);

        $this->view('receipts/show', [
            'title' => lang('finance.receipt') . ' #' . $receipt['receipt_number'],
            'breadcrumbs' => [
                ['label' => lang('finance.title'), 'url' => '/finance/invoices'],
                ['label' => lang('finance.receipts'), 'url' => '/finance/receipts'],
                ['label' => '#' . $receipt['receipt_number']],
            ],
            'receipt' => $receipt,
            'items'   => $items,
            'clubName' => Config::get('club_name_en', 'The Club'),
            'clubNameAr' => Config::get('club_name_ar', 'النادي'),
            'clubAddress' => Config::get('club_address_en', ''),
            'clubPhone' => Config::get('club_phone', ''),
        ]);
    }

    public function printReceipt(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        $db = $this->db();

        $receipt = $db->fetchOne(
            "SELECT r.*, m.full_name_en AS member_name, m.full_name_ar AS member_name_ar,
                    m.membership_number, pm.name_en AS method_name,
                    c.symbol AS currency_symbol, c.currency_code
             FROM receipts r
             LEFT JOIN members m ON r.member_id=m.id
             LEFT JOIN payment_methods pm ON r.payment_method_id=pm.id
             LEFT JOIN sys_currencies c ON r.currency_id=c.id
             WHERE r.id=?", [$id]
        );

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

        $items = $db->fetchAll("SELECT * FROM receipt_items WHERE receipt_id=? ORDER BY sort_order", [$id]);

        // Update print count
        $db->execute("UPDATE receipts SET reprint_count = reprint_count + 1, printed_at = NOW(), printed_by = ? WHERE id = ?", [Auth::id(), $id]);
        AuditLog::log('print', 'finance', 'receipt', $id, "Printed receipt {$receipt['receipt_number']}");

        $this->view('receipts/print', [
            'title'   => lang('finance.receipt') . ' #' . $receipt['receipt_number'],
            'receipt' => $receipt,
            'items'   => $items,
            'clubName' => Config::get('club_name_en', 'The Club'),
            'clubNameAr' => Config::get('club_name_ar', 'النادي'),
            'clubAddress' => Config::get('club_address_en', ''),
            'clubPhone' => Config::get('club_phone', ''),
        ], 'print');
    }
}