<?php
require_once __DIR__ . '/BaseController.php';

class AccessRuleController extends BaseController
{
    public function index(Request $request): void
    {
        $this->view('access-rules/index', [
            'title' => lang('cards.access_rules'),
            'breadcrumbs' => [['label' => lang('cards.access_control')], ['label' => lang('cards.access_rules')]],
        ]);
    }

    public function datatable(Request $request): void
    {
        $baseQuery = "SELECT acr.id, acr.rule_name, acr.member_status_required, acr.subscription_required,
                       acr.card_required, acr.allow_dependents, acr.allow_guests, acr.max_daily_entries, acr.priority, acr.is_active,
                       ap.name_en AS point_name, mt.name_en AS type_name
                       FROM access_control_rules acr
                       LEFT JOIN access_points ap ON acr.access_point_id = ap.id
                       LEFT JOIN membership_types mt ON acr.membership_type_id = mt.id
                       WHERE 1=1";
        $columns = [
            ['db' => 'id', 'searchable' => false],
            ['db' => 'rule_name', 'searchable' => true],
            ['db' => 'point_name', 'searchable' => true],
            ['db' => 'type_name', 'searchable' => true],
            ['db' => 'priority', 'searchable' => false],
            ['db' => 'is_active', 'searchable' => false],
        ];
        $this->handleDataTable($request, $baseQuery, [], $columns, 'acr.priority ASC');
    }

    public function create(Request $request): void
    {
        $db = Database::getInstance();
        $this->view('access-rules/form', [
            'title' => lang('cards.create_access_rule'),
            'breadcrumbs' => [['label' => lang('cards.access_control')], ['label' => lang('cards.access_rules'), 'url' => '/access-rules'], ['label' => lang('common.create')]],
            'rule' => null, 'formAction' => '/access-rules',
            'accessPoints' => $db->fetchAll("SELECT id, name_en FROM access_points WHERE is_active = 1 ORDER BY name_en"),
            'membershipTypes' => $db->fetchAll("SELECT id, name_en FROM membership_types WHERE is_active = 1 ORDER BY name_en"),
        ]);
    }

    public function store(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $validator = new Validator($request->all(), [
            'access_point_id' => 'required|integer|exists:access_points,id',
            'rule_name' => 'required|string|max:200',
            'member_status_required' => 'required|string|max:50',
            'priority' => 'required|integer|min:0',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['membership_type_id'] = $request->post('membership_type_id') ?: null;
        $data['subscription_required'] = $request->post('subscription_required') ? 1 : 0;
        $data['card_required'] = $request->post('card_required') ? 1 : 0;
        $data['allow_dependents'] = $request->post('allow_dependents') ? 1 : 0;
        $data['allow_guests'] = $request->post('allow_guests') ? 1 : 0;
        $data['max_daily_entries'] = $request->post('max_daily_entries') ?: null;
        $data['allowed_time_start'] = $request->post('allowed_time_start') ?: null;
        $data['allowed_time_end'] = $request->post('allowed_time_end') ?: null;
        $data['allowed_days'] = $request->post('allowed_days') ? json_encode($request->post('allowed_days')) : null;
        $data['is_active'] = $request->post('is_active') ? 1 : 0;
        $data['created_at'] = date('Y-m-d H:i:s');

        $db = Database::getInstance();
        $id = $db->insert('access_control_rules', $data);
        AuditLog::log('create', 'cards', 'access_control_rules', $id, "Access rule created");
        $this->json(['success' => true, 'message' => lang('common.success'), 'redirect' => '/access-rules']);
    }

    public function edit(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $db = Database::getInstance();
        $rule = $db->fetchOne("SELECT * FROM access_control_rules WHERE id = ?", [$id]);
        if (!$rule) { $this->abort(404, 'Not found'); return; }
        $this->view('access-rules/form', [
            'title' => lang('cards.edit_access_rule'),
            'breadcrumbs' => [['label' => lang('cards.access_control')], ['label' => lang('cards.access_rules'), 'url' => '/access-rules'], ['label' => lang('common.edit')]],
            'rule' => $rule, 'formAction' => '/access-rules/' . $id,
            'accessPoints' => $db->fetchAll("SELECT id, name_en FROM access_points WHERE is_active = 1 ORDER BY name_en"),
            'membershipTypes' => $db->fetchAll("SELECT id, name_en FROM membership_types WHERE is_active = 1 ORDER BY name_en"),
        ]);
    }

    public function update(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $id = (int) $request->routeParam('id');
        $data = [
            'access_point_id' => $request->post('access_point_id'),
            'rule_name' => $request->post('rule_name'),
            'membership_type_id' => $request->post('membership_type_id') ?: null,
            'member_status_required' => $request->post('member_status_required', 'active'),
            'subscription_required' => $request->post('subscription_required') ? 1 : 0,
            'card_required' => $request->post('card_required') ? 1 : 0,
            'allow_dependents' => $request->post('allow_dependents') ? 1 : 0,
            'allow_guests' => $request->post('allow_guests') ? 1 : 0,
            'max_daily_entries' => $request->post('max_daily_entries') ?: null,
            'allowed_time_start' => $request->post('allowed_time_start') ?: null,
            'allowed_time_end' => $request->post('allowed_time_end') ?: null,
            'allowed_days' => $request->post('allowed_days') ? json_encode($request->post('allowed_days')) : null,
            'priority' => (int) $request->post('priority', 0),
            'is_active' => $request->post('is_active') ? 1 : 0,
        ];
        $db = Database::getInstance();
        $db->update('access_control_rules', $data, 'id = ?', [$id]);
        AuditLog::log('update', 'cards', 'access_control_rules', $id, "Access rule updated");
        $this->json(['success' => true, 'message' => lang('common.success'), 'redirect' => '/access-rules']);
    }

    public function delete(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $id = (int) $request->routeParam('id');
        $db = Database::getInstance();
        $db->delete('access_control_rules', 'id = ?', [$id]);
        AuditLog::log('delete', 'cards', 'access_control_rules', $id, "Access rule deleted");
        $this->json(['success' => true, 'message' => lang('common.success')]);
    }
}