<?php

class EquipmentController extends Controller
{
    public function index(Request $request): void
    {
        $this->view('equipment/index', [
            'title' => lang('sports.equipment'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.equipment')]],
        ]);
    }

    public function create(Request $request): void
    {
        $db = $this->db();
        $sports = $db->fetchAll("SELECT id, name_en FROM sports WHERE is_active = 1 ORDER BY name_en");
        $facilities = $db->fetchAll("SELECT id, name_en FROM facilities WHERE is_active = 1 ORDER BY name_en");
        $this->view('equipment/create', [
            'title' => lang('sports.create_equipment'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.equipment'), 'url' => '/sports/equipment'], ['label' => lang('common.create')]],
            'sports' => $sports, '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(), [
            'equipment_code' => 'required|string|max:20|unique:sport_equipment,equipment_code',
            'name_en' => 'required|string|max:200',
            'name_ar' => 'required|string|max:200',
            'sport_id' => 'nullable|integer',
            'facility_id' => 'nullable|integer',
            'category' => 'nullable|string|max:50',
            'brand' => 'nullable|string|max:100',
            'quantity_total' => 'required|integer|min:1',
            'condition_status' => 'required|in:new,good,fair,poor,damaged,retired',
            'is_rentable' => 'nullable|boolean',
            'rental_fee_per_hour' => 'nullable|decimal',
            'deposit_amount' => 'nullable|decimal',
            'purchase_price' => 'nullable|decimal',
            'purchase_date' => 'nullable|date',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['quantity_available'] = $data['quantity_total'];
        $data['is_rentable'] = !empty($data['is_rentable']) ? 1 : 0;
        $data['is_active'] = 1;
        $id = $this->db()->insert('sport_equipment', $data);
        $this->audit('create', 'sport_equipment', $id, "Created equipment: {$data['name_en']}");
        $this->json(['success' => true, 'message' => 'Equipment added', 'redirect' => '/sports/equipment']);
    }

    public function edit(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        $equip = $this->db()->fetchOne("SELECT * FROM sport_equipment WHERE id = ?", [$id]);
        if (!$equip) { $this->abort(404); return; }
        $sports = $this->db()->fetchAll("SELECT id, name_en FROM sports WHERE is_active = 1 ORDER BY name_en");
        $facilities = $this->db()->fetchAll("SELECT id, name_en FROM facilities WHERE is_active = 1 ORDER BY name_en");
        $this->view('equipment/edit', [
            'title' => 'Edit: ' . $equip['name_en'],
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.equipment'), 'url' => '/sports/equipment'], ['label' => lang('common.edit')]],
            'equipment' => $equip, 'sports' => $sports, 'facilities' => $facilities,
        ]);
    }

    public function update(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $validator = new Validator($request->all(), [
            'name_en' => 'required|string|max:200',
            'name_ar' => 'required|string|max:200',
            'quantity_total' => 'required|integer|min:1',
            'condition_status' => 'required|in:new,good,fair,poor,damaged,retired',
            'is_rentable' => 'nullable|boolean',
            'rental_fee_per_hour' => 'nullable|decimal',
            'is_active' => 'nullable|boolean',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }
        $data = $validator->validated();
        $data['is_rentable'] = !empty($data['is_rentable']) ? 1 : 0;
        $data['is_active'] = !empty($data['is_active']) ? 1 : 0;
        $this->db()->update('sport_equipment', $data, 'id = ?', [$id]);
        $this->audit('update', 'sport_equipment', $id, 'Updated equipment');
        $this->json(['success' => true, 'message' => 'Equipment updated', 'redirect' => '/sports/equipment']);
    }

    public function rentals(Request $request): void
    {
        $equipment = $this->db()->fetchAll("SELECT id, name_en, equipment_code FROM sport_equipment WHERE is_rentable = 1 AND is_active = 1 AND quantity_available > 0 ORDER BY name_en");
        $this->view('equipment/rentals', [
            'title' => lang('sports.equipment_rentals'),
            'breadcrumbs' => [['label' => lang('sports.title'), 'url' => '/sports'], ['label' => lang('sports.equipment'), 'url' => '/sports/equipment'], ['label' => lang('sports.rentals')]],
            'equipment' => $equipment,
        ]);
    }

    public function storeRental(Request $request): void
    {
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $rentalNumber = SequenceGenerator::next('rental_number');
        $validator = new Validator($request->all(), [
            'equipment_id' => 'required|integer|exists:sport_equipment,id',
            'member_id' => 'required|integer|exists:members,id',
            'quantity' => 'required|integer|min:1',
            'rental_end_expected' => 'required|datetime',
        ]);
        if ($validator->fails()) { $this->json(['success' => false, 'errors' => $validator->errors()], 422); return; }

        $data = $validator->validated();
        $equip = $this->db()->fetchOne("SELECT * FROM sport_equipment WHERE id = ?", [$data['equipment_id']]);
        if ((int)$data['quantity'] > (int)$equip['quantity_available']) {
            $this->json(['success' => false, 'message' => 'Insufficient stock. Available: ' . $equip['quantity_available']], 422); return;
        }

        $feeAmount = ($equip['rental_fee_per_hour'] ?? 0) * $data['quantity'];
        $depositAmount = ($equip['deposit_amount'] ?? 0) * $data['quantity'];

        $id = $this->db()->insert('sport_equipment_rentals', [
            'rental_number' => $rentalNumber, 'equipment_id' => $data['equipment_id'],
            'member_id' => $data['member_id'], 'quantity' => $data['quantity'],
            'rental_start' => date('Y-m-d H:i:s'), 'rental_end_expected' => $data['rental_end_expected'],
            'fee_amount' => $feeAmount, 'deposit_amount' => $depositAmount,
            'status' => 'active', 'created_by' => auth_id(),
        ]);
        $this->audit('create', 'sport_equipment_rental', $id, "Rented equipment: {$rentalNumber}");
        $this->json(['success' => true, 'message' => 'Equipment rented: ' . $rentalNumber, 'redirect' => '/sports/equipment/rentals']);
    }

    public function returnRental(Request $request): void
    {
        $id = (int) $request->routeParam('id');
        if (!CSRF::validate($request->csrfToken())) { $this->json(['success' => false, 'message' => 'Invalid token'], 403); return; }
        $condition = $request->post('condition_on_return', 'good');
        $this->db()->update('sport_equipment_rentals', [
            'status' => 'returned', 'rental_end_actual' => date('Y-m-d H:i:s'),
            'condition_on_return' => $condition, 'deposit_returned' => 1,
            'deposit_returned_amount' => $condition === 'good' ? $this->db()->fetchColumn("SELECT deposit_amount FROM sport_equipment_rentals WHERE id = ?", [$id]) : 0,
        ], 'id = ?', [$id]);
        $this->audit('update', 'sport_equipment_rental', $id, "Returned rental #{$id}");
        $this->json(['success' => true, 'message' => 'Equipment returned', 'redirect' => '/sports/equipment/rentals']);
    }
}