<?php
class MembershipTypeController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('membership-types/index', [
            'title'       => lang('members.membership_types'),
            'breadcrumbs' => [
                ['label' => lang('members.title'), 'url' => '/members'],
                ['label' => lang('members.membership_types')],
            ],
        ]);
    }

    public function create(Request $request): void
    {
        $db = Database::getInstance();
        $categories = $db->fetchAll("SELECT id, name_en, name_ar FROM membership_categories WHERE is_active = 1 ORDER BY sort_order");
        $feeTypes   = $db->fetchAll("SELECT id, fee_code, name_en, name_ar FROM fee_types WHERE is_active = 1 ORDER BY sort_order");

        $this->view('membership-types/create', [
            'title'       => lang('members.create_type'),
            'breadcrumbs' => [
                ['label' => lang('members.title'), 'url' => '/members'],
                ['label' => lang('members.membership_types'), 'url' => '/membership-types'],
                ['label' => lang('common.create')],
            ],
            'categories' => $categories,
            'feeTypes'   => $feeTypes,
        ]);
    }

    public function edit(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = Database::getInstance();
        $type = $db->fetchOne("SELECT * FROM membership_types WHERE id = ?", [$id]);
        if (!$type) {
            $this->abort(404, 'Type not found');
            return;
        }

        $categories = $db->fetchAll("SELECT id, name_en, name_ar FROM membership_categories WHERE is_active = 1 ORDER BY sort_order");
        $feeTypes   = $db->fetchAll("SELECT id, fee_code, name_en, name_ar FROM fee_types WHERE is_active = 1 ORDER BY sort_order");
        $typeFees   = $db->fetchAll("SELECT mtf.*, ft.name_en AS fee_name_en FROM membership_type_fees mtf LEFT JOIN fee_types ft ON mtf.fee_type_id = ft.id WHERE mtf.membership_type_id = ? AND mtf.is_active = 1", [$id]);
        $benefits   = $db->fetchAll("SELECT * FROM membership_type_benefits WHERE membership_type_id = ? AND is_active = 1 ORDER BY sort_order", [$id]);

        $this->view('membership-types/edit', [
            'title'       => lang('common.edit') . ': ' . $type['name_en'],
            'breadcrumbs' => [
                ['label' => lang('members.title'), 'url' => '/members'],
                ['label' => lang('members.membership_types'), 'url' => '/membership-types'],
                ['label' => $type['name_en']],
            ],
            'type'       => $type,
            'categories' => $categories,
            'feeTypes'   => $feeTypes,
            'typeFees'   => $typeFees,
            'benefits'   => $benefits,
        ]);
    }
}