<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Response;
use App\Config\Database;

class UnitController extends Controller
{
    public function index(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $db = Database::getInstance();
        $stmt = $db->prepare("SELECT * FROM units WHERE tenant_id = ? OR tenant_id = 1 ORDER BY name ASC");
        $stmt->execute([$tenantId]);
        Response::success($stmt->fetchAll());
    }

    public function store(): void
    {
        $tenantId = (int) $_REQUEST['tenant_id'];
        $data = $this->getJsonBody();
        $this->validate($data, [
            'name' => 'required',
            'abbreviation' => 'required'
        ]);

        $db = Database::getInstance();
        $stmt = $db->prepare("INSERT INTO units (tenant_id, name, abbreviation) VALUES (?, ?, ?)");
        $stmt->execute([$tenantId, $data['name'], $data['abbreviation']]);
        Response::success(['id' => $db->lastInsertId()], 'Unit created', 201);
    }
}
