<?php

class LockerController extends Controller
{
    public function index(Request $request): void
    {
        $db = $this->db();
        $rooms = $db->fetchAll("SELECT lr.*, f.name_en as facility_name FROM sport_locker_rooms lr LEFT JOIN facilities f ON lr.facility_id = f.id ORDER BY lr.name_en");
        $lockers = $db->fetchAll(
            "SELECT l.*, lr.name_en as room_name,
                    (SELECT CONCAT(m.membership_number, ' - ', m.full_name_en) FROM sport_locker_assignments la JOIN members m ON la.member_id = m.id WHERE la.locker_id = l.id AND la.status = 'active' LIMIT 1) as assigned_to
             FROM sport_lockers l LEFT JOIN sport_locker_rooms lr ON l.room_id = lr.id ORDER BY lr.name_en, l.locker_number");

        $this->view('lockers/index', [
            'title' => lang('sports.lockers'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.lockers')]],
            'rooms' => $rooms, 'lockers' => $lockers,
        ]);
    }

    public function storeRoom(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $validator = new Validator($request->all(), [
            'room_code' => 'required|string|max:20|unique:sport_locker_rooms,room_code',
            'name_en' => 'required|string|max:100',
            'name_ar' => 'required|string|max:100',
            'gender' => 'required|in:male,female,unisex',
            'facility_id' => 'nullable|integer',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['is_active'] = 1;
        $this->db()->insert('sport_locker_rooms', $data);
        $this->json(['success' => true, 'message' => 'Room created', 'redirect' => '/sports/lockers']);
    }

    public function storeLocker(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $roomId = (int) $request->post('room_id');
        $count = (int) $request->post('count', 1);
        $size = $request->post('size', 'medium');
        $db = $this->db();

        $maxNumber = (int) $db->fetchColumn("SELECT COALESCE(MAX(CAST(locker_number AS UNSIGNED)), 0) FROM sport_lockers WHERE room_id = ?", [$roomId]);
        for ($i = 1; $i <= $count; $i++) {
            $num = $maxNumber + $i;
            $db->insert('sport_lockers', [
                'locker_number' => str_pad($num, 3, '0', STR_PAD_LEFT),
                'room_id' => $roomId, 'size' => $size, 'status' => 'available',
            ]);
        }
        $db->update('sport_locker_rooms', [
            'total_lockers' => $db->fetchColumn("SELECT COUNT(*) FROM sport_lockers WHERE room_id = ?", [$roomId]),
            'available_lockers' => $db->fetchColumn("SELECT COUNT(*) FROM sport_lockers WHERE room_id = ? AND status = 'available'", [$roomId]),
        ], 'id = ?', [$roomId]);

        $this->json(['success' => true, 'message' => "{$count} lockers added", 'redirect' => '/sports/lockers']);
    }

    public function assign(Request $request): void
    {
        $lockerId = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $memberId = (int) $request->post('member_id');
        $db = $this->db();
        $db->insert('sport_locker_assignments', [
            'locker_id' => $lockerId, 'member_id' => $memberId,
            'assignment_type' => $request->post('assignment_type', 'seasonal'),
            'start_date' => date('Y-m-d'), 'fee_amount' => $request->post('fee_amount', 0),
            'status' => 'active', 'key_issued' => 1,
        ]);
        $db->update('sport_lockers', ['status' => 'assigned'], 'id = ?', [$lockerId]);
        $roomId = $db->fetchColumn("SELECT room_id FROM sport_lockers WHERE id = ?", [$lockerId]);
        $db->update('sport_locker_rooms', [
            'available_lockers' => $db->fetchColumn("SELECT COUNT(*) FROM sport_lockers WHERE room_id = ? AND status = 'available'", [$roomId]),
        ], 'id = ?', [$roomId]);
        $this->json(['success' => true, 'message' => 'Locker assigned', 'redirect' => '/sports/lockers']);
    }

    public function release(Request $request): void
    {
        $lockerId = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $db = $this->db();
        $db->update('sport_locker_assignments', ['status' => 'expired', 'end_date' => date('Y-m-d'), 'key_returned' => 1], 'locker_id = ? AND status = ?', [$lockerId, 'active']);
        $db->update('sport_lockers', ['status' => 'available'], 'id = ?', [$lockerId]);
        $roomId = $db->fetchColumn("SELECT room_id FROM sport_lockers WHERE id = ?", [$lockerId]);
        $db->update('sport_locker_rooms', [
            'available_lockers' => $db->fetchColumn("SELECT COUNT(*) FROM sport_lockers WHERE room_id = ? AND status = 'available'", [$roomId]),
        ], 'id = ?', [$roomId]);
        $this->json(['success' => true, 'message' => 'Locker released', 'redirect' => '/sports/lockers']);
    }
}