<?php
class MembershipTypeApiController extends Controller
{
    public function datatable(Request $request): void
    {
        $db = Database::getInstance();
        $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 (mt.type_code LIKE ? OR mt.name_en LIKE ? OR mt.name_ar LIKE ?)";
            $s = "%{$search}%";
            $params = [$s, $s, $s];
        }

        $total = (int) $db->fetchColumn("SELECT COUNT(*) FROM membership_types mt");
        $filtered = (int) $db->fetchColumn("SELECT COUNT(*) FROM membership_types mt WHERE {$where}", $params);

        $rows = $db->fetchAll(
            "SELECT mt.*, mc.name_en AS cat_name_en,
                    (SELECT COUNT(*) FROM members m WHERE m.membership_type_id = mt.id AND m.is_deleted = 0 AND m.status = 'active') AS active_count
             FROM membership_types mt
             LEFT JOIN membership_categories mc ON mt.category_id = mc.id
             WHERE {$where}
             ORDER BY mt.sort_order
             LIMIT " . (int)$length . " OFFSET " . (int)$start,
            $params
        );

        $data = [];
        foreach ($rows as $row) {
            $actions = '<a href="/membership-types/' . $row['id'] . '/edit" class="btn btn-sm btn-outline-warning"><i class="fas fa-edit"></i></a>';
            $data[] = [
                'id'             => $row['id'],
                'type_code'      => e($row['type_code']),
                'name_en'        => e($row['name_en']),
                'name_ar'        => e($row['name_ar']),
                'category'       => e($row['cat_name_en'] ?? '—'),
                'is_family'      => $row['is_family_membership'] ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-muted"></i>',
                'max_dependents' => $row['max_dependents'] ?? '—',
                'active_count'   => number_format($row['active_count']),
                'is_active'      => $row['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>',
                'actions'        => $actions,
            ];
        }

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

    public function list(Request $request): void
    {
        $db = Database::getInstance();
        $types = $db->fetchAll("SELECT id, type_code, name_en, name_ar, is_family_membership, max_dependents FROM membership_types WHERE is_active = 1 ORDER BY sort_order");
        $this->json(['success' => true, 'data' => $types]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) {
            $this->json(['success' => false, 'message' => 'Invalid CSRF token'], 403);
            return;
        }

        $validator = new Validator($request->all(), [
            'type_code'              => 'required|string|max:30|unique:membership_types,type_code',
            'name_en'                => 'required|string|max:200',
            'name_ar'                => 'required|string|max:200',
            'category_id'            => 'nullable|integer',
            'is_family_membership'   => 'nullable|boolean',
            'max_dependents'         => 'nullable|integer|min:0',
            'requires_sponsor'       => 'nullable|boolean',
            'sponsor_count'          => 'nullable|integer|min:0',
            'requires_board_approval'=> 'nullable|boolean',
            'gender_restriction'     => 'nullable|in:male,female,both',
            'grace_period_days'      => 'nullable|integer|min:0',
            'sort_order'             => 'nullable|integer',
        ]);

        if ($validator->fails()) {
            $this->json(['success' => false, 'errors' => $validator->errors()], 422);
            return;
        }

        $data = $validator->validated();
        $data['is_family_membership']    = !empty($data['is_family_membership']) ? 1 : 0;
        $data['requires_sponsor']        = !empty($data['requires_sponsor']) ? 1 : 0;
        $data['requires_board_approval'] = !empty($data['requires_board_approval']) ? 1 : 0;
        $data['is_active'] = 1;
        $data['created_by'] = Auth::id();

        $db = Database::getInstance();
        $id = $db->insert('membership_types', $data);

        AuditLog::log('create', 'members', 'membership_types', $id, "Created membership type {$data['type_code']}");

        $this->json(['success' => true, 'message' => 'Membership type created', 'redirect' => '/membership-types/' . $id . '/edit']);
    }

    public function update(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) {
            $this->json(['success' => false, 'message' => 'Invalid CSRF token'], 403);
            return;
        }

        $id = (int) $request->routeParam('id');
        $db = Database::getInstance();
        $old = $db->fetchOne("SELECT * FROM membership_types WHERE id = ?", [$id]);
        if (!$old) {
            $this->json(['success' => false, 'message' => 'Not found'], 404);
            return;
        }

        $validator = new Validator($request->all(), [
            'name_en'                => 'required|string|max:200',
            'name_ar'                => 'required|string|max:200',
            'category_id'            => 'nullable|integer',
            'is_family_membership'   => 'nullable|boolean',
            'max_dependents'         => 'nullable|integer|min:0',
            'requires_sponsor'       => 'nullable|boolean',
            'sponsor_count'          => 'nullable|integer|min:0',
            'requires_board_approval'=> 'nullable|boolean',
            'gender_restriction'     => 'nullable|in:male,female,both',
            'grace_period_days'      => 'nullable|integer|min:0',
            'sort_order'             => 'nullable|integer',
            'is_active'              => 'nullable|boolean',
        ]);

        if ($validator->fails()) {
            $this->json(['success' => false, 'errors' => $validator->errors()], 422);
            return;
        }

        $data = $validator->validated();
        $data['is_family_membership']    = !empty($data['is_family_membership']) ? 1 : 0;
        $data['requires_sponsor']        = !empty($data['requires_sponsor']) ? 1 : 0;
        $data['requires_board_approval'] = !empty($data['requires_board_approval']) ? 1 : 0;
        $data['is_active']               = !empty($data['is_active']) ? 1 : 0;

        $db->update('membership_types', $data, 'id = ?', [$id]);

        AuditLog::log('update', 'members', 'membership_types', $id, "Updated membership type", $old, $data);

        $this->json(['success' => true, 'message' => 'Membership type updated']);
    }

    public function delete(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = Database::getInstance();
        $count = (int) $db->fetchColumn("SELECT COUNT(*) FROM members WHERE membership_type_id = ? AND is_deleted = 0", [$id]);
        if ($count > 0) {
            $this->json(['success' => false, 'message' => "Cannot delete: {$count} members are using this type"], 422);
            return;
        }
        $db->update('membership_types', ['is_active' => 0], 'id = ?', [$id]);
        $this->json(['success' => true, 'message' => 'Membership type deactivated']);
    }
}