<?php

class UserController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('users', 'view');
        $userModel = new User();
        $this->view('admin.users.index', [
            'pageTitle' => 'User Management',
            'users'     => $userModel->allWithRole(),
            'csrf'      => $this->csrfField(),
        ]);
    }

    public function create(): void
    {
        Auth::requirePermission('users', 'add');
        $roleModel = new Role();
        $this->view('admin.users.form', [
            'pageTitle' => 'Add User',
            'roles'     => $roleModel->all('role_name ASC'),
            'user'      => null,
            'csrf'      => $this->csrfField(),
        ]);
    }

    public function store(): void
    {
        Auth::requirePermission('users', 'add');
        $this->verifyCsrf();

        $userModel = new User();
        $fullName = trim($this->input('full_name', ''));
        $username = trim($this->input('username', ''));
        $password = $this->input('password', '');
        $roleId   = (int) $this->input('role_id');

        if ($fullName === '' || $username === '' || $password === '' || $roleId <= 0) {
            $this->redirect('admin/settings?tab=users');
            return;
        }
        if ($userModel->usernameExists($username)) {
            $this->redirect('admin/settings?tab=users');
            return;
        }

        $userModel->insert([
            'full_name'     => $fullName,
            'username'      => $username,
            'email'         => trim($this->input('email', '')) ?: null,
            'phone'         => trim($this->input('phone', '')) ?: null,
            'password_hash' => password_hash($password, PASSWORD_DEFAULT),
            'role_id'       => $roleId,
            'nic_number'    => trim($this->input('nic_number', '')) ?: null,
            'basic_salary'  => (float) $this->input('basic_salary', 0),
            'wage_type'     => $this->input('wage_type', 'MONTHLY'),
            'daily_wage'    => (float) $this->input('daily_wage', 0),
            'is_active'     => 1,
        ]);

        AuditLogger::log(Auth::id(), 'USER_CREATE', 'users', "Created user: {$username}");
        $this->redirect('admin/settings?tab=users');
    }

    public function edit(): void
    {
        Auth::requirePermission('users', 'edit');
        $id = (int) $this->input('id');
        $userModel = new User();
        $roleModel = new Role();
        $user = $userModel->find($id);
        if (!$user) {
            $this->redirect('admin/settings?tab=users');
            return;
        }
        $this->view('admin.users.form', [
            'pageTitle' => 'Edit User',
            'roles'     => $roleModel->all('role_name ASC'),
            'user'      => $user,
            'csrf'      => $this->csrfField(),
        ]);
    }

    public function update(): void
    {
        Auth::requirePermission('users', 'edit');
        $this->verifyCsrf();

        $id = (int) $this->input('id');
        $userModel = new User();
        $existing = $userModel->find($id);
        if (!$existing) {
            $this->redirect('admin/settings?tab=users');
            return;
        }

        // Self-protection guard: a protected user's role can't be changed (their role select is disabled
        // in the form, so no value is submitted at all — always fall back to the existing role in that case).
        $submittedRoleId = $this->input('role_id', '');
        if ($submittedRoleId === '' || $submittedRoleId === null || (bool) $existing['is_protected']) {
            $roleId = (int) $existing['role_id'];
        } else {
            $roleId = (int) $submittedRoleId;
        }

        $data = [
            'full_name'    => trim($this->input('full_name', $existing['full_name'])),
            'email'        => trim($this->input('email', '')) ?: null,
            'phone'        => trim($this->input('phone', '')) ?: null,
            'role_id'      => $roleId,
            'nic_number'   => trim($this->input('nic_number', '')) ?: null,
            'basic_salary' => (float) $this->input('basic_salary', 0),
            'wage_type'    => $this->input('wage_type', 'MONTHLY'),
            'daily_wage'   => (float) $this->input('daily_wage', 0),
            'is_active'    => (bool) $existing['is_protected'] ? 1 : (int) $this->input('is_active', 1),
        ];

        $newPassword = $this->input('password', '');
        if ($newPassword !== '') {
            $data['password_hash'] = password_hash($newPassword, PASSWORD_DEFAULT);
        }

        $userModel->update($id, $data);
        AuditLogger::log(Auth::id(), 'USER_UPDATE', 'users', "Updated user #{$id}");
        $this->redirect('admin/settings?tab=users');
    }

    public function delete(): void
    {
        Auth::requirePermission('users', 'delete');
        $this->verifyCsrf();

        $id = (int) $this->input('id');
        $userModel = new User();
        $existing = $userModel->find($id);

        if (!$existing) {
            $this->redirect('admin/settings?tab=users');
            return;
        }
        if ((bool) $existing['is_protected'] || (int) $existing['id'] === Auth::id()) {
            // Self-protection guard: cannot delete a protected account or yourself
            $this->redirect('admin/settings?tab=users');
            return;
        }

        $userModel->delete($id);
        AuditLogger::log(Auth::id(), 'USER_DELETE', 'users', "Deleted user #{$id}");
        $this->redirect('admin/settings?tab=users');
    }
}