<?php
class GuestApiController 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', '');
        $dateFrom = $request->get('date_from', '');
        $dateTo   = $request->get('date_to', '');

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

        if ($statusFilter) {
            $where .= " AND gp.status = ?";
            $params[] = $statusFilter;
        }
        if ($dateFrom) {
            $where .= " AND gp.valid_date >= ?";
            $params[] = $dateFrom;
        }
        if ($dateTo) {
            $where .= " AND gp.valid_date <= ?";
            $params[] = $dateTo;
        }
        if ($search) {
            $where .= " AND (gp.pass_number LIKE ? OR gp.guest_name 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, $s]);
        }

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

        $rows = $db->fetchAll(
            "SELECT gp.id, gp.pass_number, gp.guest_name, gp.guest_phone, gp.valid_date, gp.status, gp.fee_amount, gp.check_in_time, gp.check_out_time,
                    gpt.name_en AS type_name_en, gpt.name_ar AS type_name_ar,
                    m.membership_number, m.full_name_en AS host_name_en, m.full_name_ar AS host_name_ar
             FROM guest_passes gp
             JOIN guest_pass_types gpt ON gp.pass_type_id = gpt.id
             JOIN members m ON gp.host_member_id = m.id
             WHERE {$where}
             ORDER BY gp.id DESC
             LIMIT " . (int)$length . " OFFSET " . (int)$start,
            $params
        );

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

    public function blacklistDatatable(Request $request): void
    {
        $db = $this->db();
        $rows = $db->fetchAll(
            "SELECT gb.*, u.full_name_en AS blacklisted_by_name
             FROM guest_blacklist gb
             LEFT JOIN auth_users u ON gb.blacklisted_by = u.id
             WHERE gb.status = 'active'
             ORDER BY gb.created_at DESC"
        );

        $this->json([
            'draw'            => (int)$request->get('draw', 1),
            'recordsTotal'    => count($rows),
            'recordsFiltered' => count($rows),
            'data'            => $rows,
        ]);
    }

    public function checkBlacklist(Request $request): void
    {
        $nationalId = $request->get('national_id', '');
        $name = $request->get('name', '');
        $db = $this->db();

        $where = "status = 'active' AND (expires_at IS NULL OR expires_at >= CURDATE())";
        $params = [];

        if ($nationalId) {
            $where .= " AND guest_national_id = ?";
            $params[] = $nationalId;
        } elseif ($name) {
            $where .= " AND guest_name LIKE ?";
            $params[] = "%{$name}%";
        } else {
            $this->json(['success' => true, 'blacklisted' => false]);
            return;
        }

        $result = $this->db()->fetchOne("SELECT * FROM guest_blacklist WHERE {$where} LIMIT 1", $params);

        $this->json([
            'success'     => true,
            'blacklisted' => $result !== null,
            'data'        => $result,
        ]);
    }

    public function passTypes(Request $request): void
    {
        $types = $this->db()->fetchAll("SELECT * FROM guest_pass_types WHERE is_active = 1 ORDER BY name_en");
        $this->json(['success' => true, 'data' => $types]);
    }
}