<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Csrf;
use App\Core\DB;
use App\Core\Request;
use App\Core\Response;
use App\Core\AppBootstrap;
use App\Repositories\UserRepository;
use App\Services\UserService;
use Throwable;

final class UserController
{
    private \PDO $pdo;
    private UserRepository $users;
    private UserService $service;

    public function __construct()
    {
        $this->pdo = DB::pdo();
        $this->users = new UserRepository($this->pdo);
        $this->service = new UserService($this->pdo, $this->users);
    }

    public function handle(): void
    {
        Auth::requireLogin();
        AppBootstrap::bootUsers($this->pdo);

        if (!rbac_enabled($this->pdo)) {
            Response::flash('danger', 'يجب تشغيل ملف التحديث: sql/migrate_v1_19_auth_admin.sql');
            Response::view('pages/admin/users', ['rbac_ready' => false]);
            return;
        }

        require_permission('users.view');

        $action = (string) Request::input('action', '');
        $id = Request::int('id');

        try {
            if ($action === 'create' && Request::isPost()) {
                $this->create();
                return;
            }

            if ($action === 'save' && Request::isPost()) {
                $this->update($id);
                return;
            }

            if ($action === 'delete' && Request::isPost() && $id > 0) {
                $this->delete($id);
                return;
            }
        } catch (Throwable $e) {
            if ($this->pdo->inTransaction()) {
                $this->pdo->rollBack();
            }
            Response::flash('danger', 'خطأ: ' . $e->getMessage());
            Response::redirect('/admin/users');
            return;
        }

        $this->index($action, $id);
    }

    private function index(string $action, int $id): void
    {
        $roles = $this->users->allRoles();
        $users = $this->users->allUsersWithRoles();
        $cashboxes = $this->users->allCashboxes();

        $editUser = null;
        $editRoles = [];
        if ($action === 'edit' && $id > 0) {
            $editUser = $this->users->findById($id);
            $editRoles = $this->users->roleIdsForUser($id);
        }

        Response::view('pages/admin/users', [
            'rbac_ready' => true,
            'roles' => $roles,
            'users' => $users,
            'editUser' => $editUser,
            'editRoles' => $editRoles,
            'cashboxes' => $cashboxes,
        ]);
    }

    private function create(): void
    {
        Csrf::verify();
        require_permission('users.create');
        $uid = $this->service->create(Request::all());
        audit_log('USER_CREATE', 'users', $uid, [
            'username' => trim((string) Request::post('username', '')),
            'roles' => Request::post('role_ids', []),
        ]);
        Response::flash('success', 'تم إنشاء المستخدم');
        Response::redirect('/admin/users?action=edit&id=' . $uid);
    }

    private function update(int $id): void
    {
        Csrf::verify();
        require_permission('users.edit');
        $this->service->update($id, Request::all(), (int)current_user_id());
        audit_log('USER_UPDATE', 'users', $id, [
            'roles' => Request::post('role_ids', []),
            'active' => (Request::post('is_active') ? 1 : 0),
        ]);
        Response::flash('success', 'تم حفظ المستخدم');
        Response::redirect('/admin/users?action=edit&id=' . $id);
    }

    private function delete(int $id): void
    {
        Csrf::verify();
        require_permission('users.edit');
        $this->service->delete($id, (int)current_user_id());
        audit_log('USER_DELETE', 'users', $id, []);
        Response::flash('success', 'تم حذف المستخدم');
        Response::redirect('/admin/users');
    }
}
