<?php
declare(strict_types=1);

namespace App\Modules\Members\Controllers\Api;

use App\Core\ApiController;
use App\Core\App;
use App\Core\Request;
use App\Core\Response;
use App\Modules\Members\Models\Member;

final class MemberApiV1Controller extends ApiController
{
    public function __construct(Request $request)
    {
        parent::__construct();
        $this->request = $request;
    }

    public function index(Request $request): Response
    {
        $this->authorize('member.view');

        $page = max(1, $this->queryInt('page', 1));
        $perPage = min(100, max(1, $this->queryInt('per_page', 25)));
        $status = $this->queryParam('status');
        $search = $this->queryParam('q');
        $branchId = $this->queryParam('branch_id');

        $db = App::getInstance()->db();
        $where = ['m.is_archived = 0'];
        $params = [];

        if ($status) {
            $where[] = 'm.status = ?';
            $params[] = $status;
        }

        if ($branchId) {
            $where[] = 'm.branch_id = ?';
            $params[] = (int) $branchId;
        }

        if ($search) {
            $where[] = '(m.full_name_ar LIKE ? OR m.membership_number LIKE ? OR m.national_id LIKE ? OR m.phone_mobile LIKE ?)';
            $term = "%{$search}%";
            $params = array_merge($params, [$term, $term, $term, $term]);
        }

        $whereSql = implode(' AND ', $where);

        $countRow = $db->selectOne("SELECT COUNT(*) as total FROM members m WHERE {$whereSql}", $params);
        $total = (int) ($countRow['total'] ?? 0);

        $offset = ($page - 1) * $perPage;
        $rows = $db->select(
            "SELECT m.id, m.membership_number, m.full_name_ar, m.full_name_en, m.national_id, m.phone_mobile, m.status, m.membership_type, m.branch_id, m.created_at
             FROM members m
             WHERE {$whereSql}
             ORDER BY m.id DESC
             LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        return $this->paginatedResponse($rows, $total, $page, $perPage);
    }

    public function show(Request $request, string $id): Response
    {
        $this->authorize('member.view');

        $member = Member::find((int) $id);
        if (!$member || $member->is_archived) {
            return $this->errorResponse('العضو غير موجود', 404);
        }

        $data = [
            'id' => $member->id,
            'membership_number' => $member->membership_number,
            'full_name_ar' => $member->full_name_ar,
            'full_name_en' => $member->full_name_en,
            'national_id' => $member->national_id,
            'date_of_birth' => $member->date_of_birth,
            'gender' => $member->gender,
            'phone_mobile' => $member->phone_mobile,
            'email' => $member->email,
            'status' => $member->status,
            'membership_type' => $member->membership_type,
            'member_category' => $member->member_category,
            'branch_id' => $member->branch_id,
            'branch_name' => $member->getBranchName(),
            'created_at' => $member->created_at,
        ];

        return $this->successResponse($data);
    }

    public function search(Request $request): Response
    {
        $this->authorize('member.view');

        $q = trim((string) $this->queryParam('q', ''));
        if ($q === '' || mb_strlen($q) < 2) {
            return $this->successResponse([]);
        }

        $db = App::getInstance()->db();
        $term = "%{$q}%";
        $rows = $db->select(
            "SELECT id, membership_number, full_name_ar, phone_mobile, status
             FROM members
             WHERE is_archived = 0
               AND (full_name_ar LIKE ? OR membership_number LIKE ? OR national_id LIKE ? OR phone_mobile LIKE ?)
             ORDER BY full_name_ar ASC
             LIMIT 20",
            [$term, $term, $term, $term]
        );

        return $this->successResponse($rows);
    }
}
