<?php
class CardController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();
        $stats = [
            'total_active'   => (int)$db->fetchColumn("SELECT COUNT(*) FROM member_cards WHERE status='active'"),
            'expiring_30'    => (int)$db->fetchColumn("SELECT COUNT(*) FROM member_cards WHERE status='active' AND expiry_date IS NOT NULL AND expiry_date BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)"),
            'lost_stolen'    => (int)$db->fetchColumn("SELECT COUNT(*) FROM member_cards WHERE status IN ('lost','stolen')"),
            'expired'        => (int)$db->fetchColumn("SELECT COUNT(*) FROM member_cards WHERE status='expired'"),
        ];

        $this->view('cards/index', [
            'title'       => lang('cards.all_cards'),
            'breadcrumbs' => [
                ['label' => lang('cards.module'), 'url' => '/cards'],
                ['label' => lang('cards.all_cards')],
            ],
            'stats' => $stats,
        ]);
    }

    public function show(Request $request): void
    {
        $id = (int)$request->routeParam('id');
        $db = $this->db();

        $card = $db->fetchOne(
            "SELECT mc.*, ct.name_en AS type_name_en, ct.name_ar AS type_name_ar,
                    m.membership_number, m.full_name_en AS member_name_en, m.full_name_ar AS member_name_ar,
                    m.primary_phone, m.photo_path AS member_photo,
                    md.full_name_en AS dep_name_en, md.full_name_ar AS dep_name_ar
             FROM member_cards mc
             JOIN card_types ct ON mc.card_type_id = ct.id
             LEFT JOIN members m ON mc.member_id = m.id
             LEFT JOIN member_dependents md ON mc.dependent_id = md.id
             WHERE mc.id = ?", [$id]
        );

        if (!$card) {
            $this->abort(404, 'Card not found');
        }

        $accessLog = $db->fetchAll(
            "SELECT mal.*, ap.name_en AS point_name_en, ap.name_ar AS point_name_ar
             FROM member_access_log mal
             LEFT JOIN access_points ap ON mal.access_point_id = ap.id
             WHERE mal.card_id = ?
             ORDER BY mal.access_time DESC LIMIT 20", [$id]
        );

        $replacementHistory = $db->fetchAll(
            "SELECT * FROM member_cards WHERE replaced_by_card_id = ? OR replaces_card_id = ? ORDER BY created_at DESC",
            [$id, $id]
        );

        $this->view('cards/show', [
            'title'       => lang('cards.card_details'),
            'breadcrumbs' => [
                ['label' => lang('cards.module'), 'url' => '/cards'],
                ['label' => $card['card_number']],
            ],
            'card'        => $card,
            'accessLog'   => $accessLog,
            'history'     => $replacementHistory,
        ]);
    }

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

        $id = (int)$request->routeParam('id');
        $reason = trim($request->post('reason', ''));
        $newStatus = $request->post('new_status', 'cancelled');

        if (!in_array($newStatus, ['lost', 'stolen', 'damaged', 'cancelled', 'suspended'])) {
            $this->json(['success' => false, 'message' => 'Invalid status'], 422);
            return;
        }

        if (empty($reason)) {
            $this->json(['success' => false, 'errors' => ['reason' => ['Reason is required']]], 422);
            return;
        }

        $db = $this->db();
        $card = $db->fetchOne("SELECT * FROM member_cards WHERE id = ? AND status = 'active'", [$id]);

        if (!$card) {
            $this->json(['success' => false, 'message' => 'Active card not found'], 404);
            return;
        }

        $db->update('member_cards', [
            'status'            => $newStatus,
            'status_reason'     => $reason,
            'status_changed_at' => date('Y-m-d H:i:s'),
        ], 'id = ?', [$id]);

        $this->audit('update', 'member_cards', $id, "Card invalidated: {$newStatus}", $card, ['status' => $newStatus, 'status_reason' => $reason]);

        $this->json(['success' => true, 'message' => lang('cards.card_invalidated')]);
    }
}