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

    public function create(Request $request): void
    {
        $db = $this->db();
        $membershipTypes = $db->fetchAll("SELECT id, name_en, name_ar FROM membership_types WHERE is_active = 1 ORDER BY sort_order");

        $this->view('periods/create', [
            'title' => lang('applications.create_period'),
            'breadcrumbs' => [
                ['label' => lang('applications.title'), 'url' => '/applications'],
                ['label' => lang('applications.periods'), 'url' => '/application-periods'],
                ['label' => lang('common.create')]
            ],
            'membershipTypes' => $membershipTypes,
            'period' => null,
        ]);
    }

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

        $validator = new Validator($request->all(), [
            'period_name_en' => 'required|string|max:200',
            'period_name_ar' => 'required|string|max:200',
            'start_date'     => 'required|date',
            'end_date'       => 'required|date',
        ]);

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

        $typeIds = $request->post('membership_type_ids', []);

        $id = $this->db()->insert('application_periods', [
            'period_name_en'     => $request->post('period_name_en'),
            'period_name_ar'     => $request->post('period_name_ar'),
            'start_date'         => $request->post('start_date'),
            'end_date'           => $request->post('end_date'),
            'membership_type_ids'=> !empty($typeIds) ? json_encode($typeIds) : null,
            'max_applications'   => $request->post('max_applications') ?: null,
            'is_active'          => $request->post('is_active', 1),
            'created_by'         => Auth::id(),
        ]);

        $this->audit('create', 'application_periods', $id, 'Application period created');
        $this->json(['success' => true, 'message' => lang('applications.period_created'), 'redirect' => '/application-periods']);
    }

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

        $membershipTypes = $db->fetchAll("SELECT id, name_en, name_ar FROM membership_types WHERE is_active = 1 ORDER BY sort_order");

        $this->view('periods/create', [
            'title' => lang('applications.edit_period'),
            'breadcrumbs' => [
                ['label' => lang('applications.title'), 'url' => '/applications'],
                ['label' => lang('applications.periods'), 'url' => '/application-periods'],
                ['label' => lang('common.edit')]
            ],
            'membershipTypes' => $membershipTypes,
            'period' => $period,
        ]);
    }

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

        $typeIds = $request->post('membership_type_ids', []);

        $this->db()->update('application_periods', [
            'period_name_en'      => $request->post('period_name_en'),
            'period_name_ar'      => $request->post('period_name_ar'),
            'start_date'          => $request->post('start_date'),
            'end_date'            => $request->post('end_date'),
            'membership_type_ids' => !empty($typeIds) ? json_encode($typeIds) : null,
            'max_applications'    => $request->post('max_applications') ?: null,
            'is_active'           => $request->post('is_active', 1),
        ], 'id = ?', [$id]);

        $this->audit('update', 'application_periods', $id, 'Application period updated');
        $this->json(['success' => true, 'message' => lang('applications.period_updated'), 'redirect' => '/application-periods']);
    }
}