<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Request;
use App\Core\Validator;
use App\Models\Account;
use App\Models\AuditLog;
use App\Models\Equipment;

final class EquipmentController extends BaseController
{
    public function index(Request $request): void
    {
        $this->requireModule('equipment');
        $status = (string) ($_GET['status'] ?? 'active');
        if (!in_array($status, ['all', 'active', 'retired'], true)) {
            $status = 'active';
        }
        $accountId = (int) ($_GET['account'] ?? 0);
        $page = $this->page();
        $result = Equipment::paginate($accountId > 0 ? $accountId : null, $status, $this->q(), $page, 20);
        view('equipment/index', [
            'title' => 'Equipment',
            'rows' => $result['rows'],
            'total' => $result['total'],
            'page' => $page,
            'pages' => max(1, (int) ceil($result['total'] / 20)),
            'q' => $this->q(),
            'status' => $status,
            'accountId' => $accountId,
            'counts' => Equipment::counts(),
            'accounts' => Account::allForSelect(),
            'notifications' => $this->notifications(),
        ]);
    }

    public function store(Request $request): void
    {
        $this->requireModule('equipment');
        $this->verifyCsrf($request);
        $data = $request->all();
        $v = (new Validator())->required($data, ['account_id' => 'Account', 'name' => 'Name']);
        if ($v->fails()) {
            $this->fail($v);
        }
        $account = Account::find((int) $data['account_id']);
        if (!$account) {
            json_out(['ok' => false, 'error' => 'Account not found.'], 404);
        }
        $id = Equipment::create([
            'account_id' => (int) $account['id'],
            'name' => $data['name'],
            'model' => $data['model'] ?? null,
            'serial_no' => $data['serial_no'] ?? null,
            'location' => $data['location'] ?? null,
            'status' => 'active',
            'installed_at' => $data['installed_at'] ?: null,
        ]);
        AuditLog::write('equipment.create', 'equipment', $id);
        json_out(['ok' => true, 'message' => 'Equipment saved on the customer.']);
    }
}
