<?php
class UnitController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('products.view');
        $units = Database::fetchAll('SELECT u.*,(SELECT COUNT(*) FROM products WHERE unit_id=u.id) AS product_count FROM units u ORDER BY u.unit_name');
        $pageTitle='Units';
        ob_start(); require APP_PATH.'/views/units/index.php'; $content=ob_get_clean();
        require APP_PATH.'/views/layouts/main.php';
    }
    public function store(): void
    {
        Auth::requirePermission('products.create'); Auth::requireCsrf();
        Database::insert('INSERT INTO units (unit_name,short_name) VALUES (?,?)',
            [trim($this->post('unit_name','')),trim($this->post('short_name',''))]);
        redirectWith(APP_URL.'/units','success','Unit added.');
    }
    public function update(string $id): void
    {
        Auth::requirePermission('products.edit'); Auth::requireCsrf();
        Database::execute('UPDATE units SET unit_name=?,short_name=? WHERE id=?',
            [trim($this->post('unit_name','')),trim($this->post('short_name','')),(int)$id]);
        redirectWith(APP_URL.'/units','success','Unit updated.');
    }
    public function delete(string $id): void
    {
        Auth::requirePermission('products.delete'); Auth::requireCsrf();
        Database::execute('DELETE FROM units WHERE id=?',[(int)$id]);
        redirectWith(APP_URL.'/units','success','Unit deleted.');
    }
}
