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

class AccessLogController extends BaseController
{
    public function index(Request $request): void
    {
        $db = Database::getInstance();
        $todayEntries = (int) $db->fetchColumn("SELECT COUNT(*) FROM member_access_log WHERE DATE(access_time) = CURDATE() AND direction = 'entry' AND granted = 1");
        $todayDenied = (int) $db->fetchColumn("SELECT COUNT(*) FROM member_access_log WHERE DATE(access_time) = CURDATE() AND granted = 0");
        $accessPoints = $db->fetchAll("SELECT id, name_en FROM access_points WHERE is_active = 1 ORDER BY name_en");

        $this->view('access-log/index', [
            'title' => lang('cards.access_log'),
            'breadcrumbs' => [['label' => lang('cards.access_control')], ['label' => lang('cards.access_log')]],
            'todayEntries' => $todayEntries,
            'todayDenied' => $todayDenied,
            'accessPoints' => $accessPoints,
        ]);
    }

    public function datatable(Request $request): void
    {
        $pointId = $request->get('filter_point', '');
        $direction = $request->get('filter_direction', '');
        $dateFrom = $request->get('filter_date_from', '');
        $dateTo = $request->get('filter_date_to', '');

        $where = "WHERE 1=1";
        $params = [];
        if ($pointId) { $where .= " AND mal.access_point_id = ?"; $params[] = $pointId; }
        if ($direction) { $where .= " AND mal.direction = ?"; $params[] = $direction; }
        if ($dateFrom) { $where .= " AND DATE(mal.access_time) >= ?"; $params[] = $dateFrom; }
        if ($dateTo) { $where .= " AND DATE(mal.access_time) <= ?"; $params[] = $dateTo; }
        if (!$dateFrom && !$dateTo) { $where .= " AND DATE(mal.access_time) = CURDATE()"; }

        $baseQuery = "SELECT mal.id, mal.direction, mal.access_time, mal.access_method, mal.granted, mal.denial_reason,
                       ap.name_en AS point_name,
                       m.membership_number, m.full_name_en AS member_name,
                       mc.card_number
                       FROM member_access_log mal
                       LEFT JOIN access_points ap ON mal.access_point_id = ap.id
                       LEFT JOIN members m ON mal.member_id = m.id
                       LEFT JOIN member_cards mc ON mal.card_id = mc.id
                       {$where}";

        $columns = [
            ['db' => 'id', 'searchable' => false],
            ['db' => 'access_time', 'searchable' => false],
            ['db' => 'direction', 'searchable' => false],
            ['db' => 'member_name', 'searchable' => true],
            ['db' => 'membership_number', 'searchable' => true],
            ['db' => 'point_name', 'searchable' => true],
            ['db' => 'access_method', 'searchable' => false],
            ['db' => 'granted', 'searchable' => false],
            ['db' => 'card_number', 'searchable' => true],
        ];

        $this->handleDataTable($request, $baseQuery, $params, $columns, 'mal.access_time DESC');
    }

    public function record(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',
            'direction' => 'required|in:entry,exit',
            'access_method' => 'required|in:card,barcode,qr,rfid,fingerprint,face,manual',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }

        $db = Database::getInstance();
        $memberId = $request->post('member_id') ?: null;
        $cardId = $request->post('card_id') ?: null;
        $guestPassId = $request->post('guest_pass_id') ?: null;
        $granted = 1;
        $denialReason = null;

        // Validate access if member
        if ($memberId) {
            $member = $db->fetchOne("SELECT status FROM members WHERE id = ? AND is_deleted = 0", [$memberId]);
            if (!$member || $member['status'] !== 'active') {
                $granted = 0;
                $denialReason = 'Member not active (status: ' . ($member['status'] ?? 'not found') . ')';
            }
        }

        $id = $db->insert('member_access_log', [
            'access_point_id' => $request->post('access_point_id'),
            'member_id' => $memberId,
            'dependent_id' => $request->post('dependent_id') ?: null,
            'card_id' => $cardId,
            'guest_pass_id' => $guestPassId,
            'direction' => $request->post('direction'),
            'access_method' => $request->post('access_method'),
            'granted' => $granted,
            'denial_reason' => $denialReason,
            'notes' => $request->post('notes', ''),
        ]);

        $this->json(['success' => true, 'message' => $granted ? lang('cards.access_granted') : lang('cards.access_denied'), 'granted' => (bool) $granted]);
    }
}