<?php
class CarnetApiController extends Controller
{
    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'] ?? '';
        $statusFilter = $request->get('status', '');

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

        if ($statusFilter) {
            $where .= " AND c.status = ?";
            $params[] = $statusFilter;
        }
        if ($search) {
            $where .= " AND (c.carnet_number LIKE ? OR m.full_name_en LIKE ? OR m.full_name_ar LIKE ? OR m.membership_number LIKE ?)";
            $s = "%{$search}%";
            $params = array_merge($params, [$s, $s, $s, $s]);
        }

        $totalAll = (int)$db->fetchColumn("SELECT COUNT(*) FROM carnets c LEFT JOIN members m ON c.member_id = m.id");
        $totalFiltered = (int)$db->fetchColumn(
            "SELECT COUNT(*) FROM carnets c LEFT JOIN members m ON c.member_id = m.id WHERE {$where}", $params
        );

        $rows = $db->fetchAll(
            "SELECT c.id, c.carnet_number, c.purchase_date, c.expiry_date, c.total_entries, c.used_entries, c.remaining_entries, c.status, c.price_paid,
                    ct.name_en AS type_name_en, ct.name_ar AS type_name_ar,
                    m.membership_number, m.full_name_en AS member_name_en, m.full_name_ar AS member_name_ar
             FROM carnets c
             JOIN carnet_types ct ON c.carnet_type_id = ct.id
             JOIN members m ON c.member_id = m.id
             WHERE {$where}
             ORDER BY c.id DESC
             LIMIT " . (int)$length . " OFFSET " . (int)$start,
            $params
        );

        $this->json([
            'draw'            => $draw,
            'recordsTotal'    => $totalAll,
            'recordsFiltered' => $totalFiltered,
            'data'            => $rows,
        ]);
    }

    public function typesDatatable(Request $request): void
    {
        $rows = $this->db()->fetchAll("SELECT * FROM carnet_types ORDER BY name_en");
        $this->json([
            'draw'            => (int)$request->get('draw', 1),
            'recordsTotal'    => count($rows),
            'recordsFiltered' => count($rows),
            'data'            => $rows,
        ]);
    }

    public function entries(Request $request): void
    {
        $carnetId = (int)$request->routeParam('id');
        $entries = $this->db()->fetchAll(
            "SELECT ce.*, f.name_en AS facility_name_en, f.name_ar AS facility_name_ar, u.full_name_en AS recorded_by_name
             FROM carnet_entries ce
             LEFT JOIN facilities f ON ce.facility_id = f.id
             LEFT JOIN auth_users u ON ce.recorded_by = u.id
             WHERE ce.carnet_id = ?
             ORDER BY ce.entry_date DESC, ce.entry_time DESC", [$carnetId]
        );
        $this->json(['success' => true, 'data' => $entries]);
    }
}