<?php

class UserController extends Controller
{
    private User $users;
    private Driver $drivers;
    private Carrier $carriers;

    public function __construct()
    {
        $this->users = new User();
        $this->drivers = new Driver();
        $this->carriers = new Carrier();
    }

    public function index(): void
    {
        Auth::requireRole(['owner','admin']);
        $search = trim((string) ($_GET['search'] ?? ''));
        $users = $this->users->all($search ?: null);
        $this->view('users/index', compact('users','search'));
        clear_old();
    }

    public function create(): void
    {
        Auth::requireRole(['owner','admin']);
        $userRecord = null;
        $drivers = $this->drivers->all();
        $carriers = $this->carriers->active();
        $roles = User::ROLES;
        $this->view('users/create', compact('userRecord','drivers','carriers','roles'));
    }

    public function store(): void
    {
        Auth::requireRole(['owner','admin']);
        Csrf::verify();
        $error = $this->validationError($_POST, true);
        if ($error) {
            set_old($_POST);
            $this->flash('danger', $error);
            $this->redirect('/users/create');
        }
        $this->users->create($_POST);
        log_activity('user_created', 'Created user ' . trim((string) $_POST['email']));
        $this->flash('success', 'User created successfully.');
        $this->redirect('/users');
    }

    public function edit(): void
    {
        Auth::requireRole(['owner','admin']);
        $userRecord = $this->users->find((int) ($_GET['id'] ?? 0));
        if (!$userRecord) {
            $this->flash('danger', 'User not found.');
            $this->redirect('/users');
        }
        $drivers = $this->drivers->all();
        $carriers = $this->carriers->active();
        $roles = User::ROLES;
        $this->view('users/edit', compact('userRecord','drivers','carriers','roles'));
    }

    public function update(): void
    {
        Auth::requireRole(['owner','admin']);
        Csrf::verify();
        $id = (int) ($_POST['id'] ?? 0);
        $error = !$id ? 'User not found.' : $this->validationError($_POST, false);
        if ($error) {
            set_old($_POST);
            $this->flash('danger', $error);
            $this->redirect('/users/edit?id=' . $id);
        }
        $this->users->update($id, $_POST);
        log_activity('user_updated', 'Updated user ' . trim((string) $_POST['email']));
        $this->flash('success', 'User updated successfully.');
        $this->redirect('/users');
    }

    public function delete(): void
    {
        Auth::requireRole(['owner','admin']);
        Csrf::verify();
        $this->users->delete((int) ($_POST['id'] ?? 0));
        log_activity('user_deleted', 'Deleted user');
        $this->flash('success', 'User deleted successfully.');
        $this->redirect('/users');
    }

    private function validationError(array $data, bool $requirePassword): ?string
    {
        if (trim((string) ($data['name'] ?? '')) === '' || !filter_var($data['email'] ?? '', FILTER_VALIDATE_EMAIL)) {
            return 'Name and a valid email address are required.';
        }
        if ($requirePassword && strlen((string) ($data['password'] ?? '')) < 8) {
            return 'Password must contain at least 8 characters.';
        }
        if (!$requirePassword && !empty($data['password']) && strlen((string) $data['password']) < 8) {
            return 'A new password must contain at least 8 characters.';
        }
        $role = in_array(($data['role'] ?? ''), User::ROLES, true) ? $data['role'] : 'dispatcher';
        if ($role === 'driver' && empty($data['driver_id'])) {
            return 'Select the driver record linked to this Driver portal account.';
        }
        if ($role === 'carrier' && empty($data['carrier_id'])) {
            return 'Select the carrier company linked to this Carrier portal account.';
        }
        return null;
    }
}
