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

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

    public function datatable(Request $request): void
    {
        $baseQuery = "SELECT ap.id, ap.point_code, ap.name_en, ap.name_ar, ap.location, ap.point_type, ap.hardware_type, ap.direction, ap.is_active,
                       f.name_en AS facility_name
                       FROM access_points ap
                       LEFT JOIN facilities f ON ap.facility_id = f.id
                       WHERE 1=1";
        $columns = [
            ['db' => 'id', 'searchable' => false],
            ['db' => 'point_code', 'searchable' => true],
            ['db' => 'name_en', 'searchable' => true],
            ['db' => 'location', 'searchable' => true],
            ['db' => 'point_type', 'searchable' => true],
            ['db' => 'is_active', 'searchable' => false],
        ];
        $this->handleDataTable($request, $baseQuery, [], $columns, 'ap.id ASC');
    }

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

    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(), [
            'point_code' => 'required|string|max:20|unique:access_points,point_code',
            'name_en' => 'required|string|max:200', 'name_ar' => 'required|string|max:200',
            'point_type' => 'required|in:main_gate,facility_entrance,parking,pool,gym,court,other',
            'hardware_type' => 'required|in:turnstile,gate,door,barrier,scanner,manual',
            'direction' => 'required|in:entry,exit,both',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['facility_id'] = $request->post('facility_id') ?: null;
        $data['location'] = $request->post('location', '');
        $data['hardware_id'] = $request->post('hardware_id', '');
        $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_points', $data);
        AuditLog::log('create', 'cards', 'access_points', $id, "Access point {$data['point_code']} created");
        $this->json(['success' => true, 'message' => lang('common.success'), 'redirect' => '/access-points']);
    }

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

    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');
        $validator = new Validator($request->all(), [
            'point_code' => "required|string|max:20|unique:access_points,point_code,{$id}",
            'name_en' => 'required|string|max:200', 'name_ar' => 'required|string|max:200',
            'point_type' => 'required|in:main_gate,facility_entrance,parking,pool,gym,court,other',
            'hardware_type' => 'required|in:turnstile,gate,door,barrier,scanner,manual',
            'direction' => 'required|in:entry,exit,both',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['facility_id'] = $request->post('facility_id') ?: null;
        $data['location'] = $request->post('location', '');
        $data['hardware_id'] = $request->post('hardware_id', '');
        $data['is_active'] = $request->post('is_active') ? 1 : 0;

        $db = Database::getInstance();
        $db->update('access_points', $data, 'id = ?', [$id]);
        AuditLog::log('update', 'cards', 'access_points', $id, "Access point updated");
        $this->json(['success' => true, 'message' => lang('common.success'), 'redirect' => '/access-points']);
    }
}