<?php
class MembershipCategoryApiController extends Controller
{
    public function datatable(Request $request): void
    {
        $db = Database::getInstance();
        $rows = $db->fetchAll(
            "SELECT mc.*, (SELECT COUNT(*) FROM membership_types mt WHERE mt.category_id = mc.id) AS type_count
             FROM membership_categories mc ORDER BY mc.sort_order"
        );

        $data = [];
        foreach ($rows as $row) {
            $actions = '<div class="btn-group btn-group-sm">';
            $actions .= '<button class="btn btn-outline-warning btn-edit-cat" data-id="' . $row['id'] . '" data-code="' . e($row['category_code']) . '" data-name-en="' . e($row['name_en']) . '" data-name-ar="' . e($row['name_ar']) . '" data-sort="' . $row['sort_order'] . '"><i class="fas fa-edit"></i></button>';
            if ($row['type_count'] == 0) {
                $actions .= '<button class="btn btn-outline-danger btn-delete-cat" data-id="' . $row['id'] . '"><i class="fas fa-trash"></i></button>';
            }
            $actions .= '</div>';

            $data[] = [
                'id'         => $row['id'],
                'code'       => e($row['category_code']),
                'name_en'    => e($row['name_en']),
                'name_ar'    => e($row['name_ar']),
                'type_count' => $row['type_count'],
                'is_active'  => $row['is_active'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>',
                'sort_order' => $row['sort_order'],
                'actions'    => $actions,
            ];
        }

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

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

    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(), [
            'category_code' => 'required|string|max:20|unique:membership_categories,category_code',
            'name_en'       => 'required|string|max:200',
            'name_ar'       => 'required|string|max:200',
            'sort_order'    => 'nullable|integer',
        ]);

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

        $db = Database::getInstance();
        $id = $db->insert('membership_categories', array_merge($validator->validated(), ['is_active' => 1]));

        $this->json(['success' => true, 'message' => 'Category created', 'id' => $id]);
    }

    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');
        $validator = new Validator($request->all(), [
            'name_en'    => 'required|string|max:200',
            'name_ar'    => 'required|string|max:200',
            'sort_order' => 'nullable|integer',
        ]);

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

        Database::getInstance()->update('membership_categories', $validator->validated(), 'id = ?', [$id]);
        $this->json(['success' => true, 'message' => 'Category updated']);
    }

    public function delete(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = Database::getInstance();
        $count = (int) $db->fetchColumn("SELECT COUNT(*) FROM membership_types WHERE category_id = ?", [$id]);
        if ($count > 0) {
            $this->json(['success' => false, 'message' => 'Cannot delete: used by membership types'], 422);
            return;
        }
        $db->delete('membership_categories', 'id = ?', [$id]);
        $this->json(['success' => true, 'message' => 'Category deleted']);
    }
}