<?php

declare(strict_types=1);

namespace App\Modules\Workspace;

use App\Core\BaseController;
use App\Core\Request;
use App\Core\Session;

/**
 * WorkspaceUserController — Coordinates User Management actions inside the Couple Portal.
 */
class WorkspaceUserController extends BaseController
{
    protected string $layout = 'couple';
    private WorkspaceUserModel $model;

    public function __construct()
    {
        $this->model = new WorkspaceUserModel();
    }

    /**
     * List all users associated with the active workspace.
     */
    public function index(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');
        $users = $this->model->getUsersByWorkspaceId($workspaceId);

        $this->render('workspace/users/index', [
            'title' => 'Workspace Users',
            'users' => $users,
            'success' => Session::get('success') ?? null
        ]);

        Session::set('success', null);
    }

    /**
     * Render the creation form.
     */
    public function create(Request $request): void
    {
        $this->render('workspace/users/create', [
            'title' => 'Add Workspace User',
            'old' => Session::get('old_input') ?? [],
            'errors' => Session::get('errors') ?? []
        ]);

        Session::set('old_input', null);
        Session::set('errors', null);
    }

    /**
     * Process creation submission.
     */
    public function store(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');
        $postData = $request->allPost();

        $displayName = trim((string) ($postData['display_name'] ?? ''));
        $username = trim((string) ($postData['username'] ?? ''));
        $password = (string) ($postData['password'] ?? '');
        $roleId = 2; // Force Couple (role_id 2)
        $isActive = (int) ($postData['is_active'] ?? 1);

        $errors = [];

        if ($displayName === '') {
            $errors['display_name'] = 'Display Name is required.';
        }
        if ($username === '') {
            $errors['username'] = 'Username is required.';
        } elseif (!preg_match('/^[a-zA-Z0-9_\-]+$/', $username)) {
            $errors['username'] = 'Username can only contain letters, numbers, dashes, and underscores.';
        } elseif ($this->model->usernameExists($username)) {
            $errors['username'] = "The username '{$username}' is already taken.";
        }

        if ($password === '') {
            $errors['password'] = 'Password is required.';
        } elseif (strlen($password) < 6) {
            $errors['password'] = 'Password must be at least 6 characters.';
        }

        if (!empty($errors)) {
            Session::set('errors', $errors);
            Session::set('old_input', $postData);
            $this->flash('error', 'Please correct validation errors.');
            $this->redirect('/app/couple/users/create');
            return;
        }

        // Insert
        try {
            $this->model->insertUser([
                'workspace_id'  => $workspaceId,
                'role_id'       => $roleId,
                'email'         => "{$username}@inveetaire.local",
                'username'      => $username,
                'password_hash' => password_hash($password, PASSWORD_DEFAULT),
                'display_name'  => $displayName,
                'is_active'     => $isActive
            ]);

            Session::set('success', "Workspace user '{$username}' created successfully!");
            $this->redirect('/app/couple/users');
        } catch (\Throwable $e) {
            $this->flash('error', 'Failed to create user: ' . $e->getMessage());
            Session::set('old_input', $postData);
            $this->redirect('/app/couple/users/create');
        }
    }

    /**
     * Render the edit form.
     */
    public function edit(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');
        $userId = (int) $request->param('id');

        $user = $this->model->getUserByIdAndWorkspace($userId, $workspaceId);
        if ($user === null) {
            $this->flash('error', 'User not found in this workspace.');
            $this->redirect('/app/couple/users');
            return;
        }

        $this->render('workspace/users/edit', [
            'title' => 'Edit Workspace User',
            'user' => $user,
            'errors' => Session::get('errors') ?? [],
            'error' => Session::get('error') ?? null
        ]);

        Session::set('errors', null);
        Session::set('error', null);
    }

    /**
     * Process edit submission.
     */
    public function update(Request $request): void
    {
        $workspaceId = (int) Session::get('active_workspace_id');
        $userId = (int) $request->param('id');
        $postData = $request->allPost();

        $user = $this->model->getUserByIdAndWorkspace($userId, $workspaceId);
        if ($user === null) {
            $this->flash('error', 'User not found in this workspace.');
            $this->redirect('/app/couple/users');
            return;
        }

        $displayName = trim((string) ($postData['display_name'] ?? ''));
        $username = trim((string) ($postData['username'] ?? ''));
        $password = (string) ($postData['password'] ?? '');
        $roleId = 2; // Force Couple (role_id 2)
        $isActive = (int) ($postData['is_active'] ?? 1);

        $errors = [];

        if ($displayName === '') {
            $errors['display_name'] = 'Display Name is required.';
        }
        if ($username === '') {
            $errors['username'] = 'Username is required.';
        } elseif (!preg_match('/^[a-zA-Z0-9_\-]+$/', $username)) {
            $errors['username'] = 'Username can only contain letters, numbers, dashes, and underscores.';
        } elseif ($this->model->usernameExists($username, $userId)) {
            $errors['username'] = "The username '{$username}' is already taken.";
        }

        if ($password !== '' && strlen($password) < 6) {
            $errors['password'] = 'Password must be at least 6 characters.';
        }

        if (!empty($errors)) {
            Session::set('errors', $errors);
            $this->flash('error', 'Please correct validation errors.');
            $this->redirect("/app/couple/users/edit/{$userId}");
            return;
        }

        try {
            $updateData = [
                'display_name' => $displayName,
                'username'     => $username,
                'role_id'      => $roleId,
                'is_active'    => $isActive,
                'email'        => "{$username}@inveetaire.local"
            ];

            if ($isActive === 0) {
                $updateData['deactivated_at'] = date('Y-m-d H:i:s');
            } else {
                $updateData['deactivated_at'] = null;
            }

            if ($password !== '') {
                $updateData['password_hash'] = password_hash($password, PASSWORD_DEFAULT);
            }

            $this->model->updateUser($userId, $workspaceId, $updateData);

            Session::set('success', "Workspace user '{$username}' updated successfully!");
            $this->redirect('/app/couple/users');
        } catch (\Throwable $e) {
            $this->flash('error', 'Failed to update user: ' . $e->getMessage());
            $this->redirect("/app/couple/users/edit/{$userId}");
        }
    }
}
