<?php

declare(strict_types=1);

namespace App\Modules\Workspace;

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

/**
 * WorkspaceController — Coordinates refined multi-step workspace provisioning (RC-016B)
 */
class WorkspaceController extends BaseController
{
    protected string $layout = 'admin';

    /**
     * Step 1: Create Workspace GET form.
     */
    public function create(Request $request): void
    {
        $this->render('workspace/create', [
            'title'  => 'Provision Workspace - Step 1',
            'old'    => Session::get('old_input') ?? [],
            'errors' => Session::get('errors') ?? []
        ]);
        Session::set('old_input', null);
        Session::set('errors', null);
    }

    /**
     * Step 1: Create Workspace POST submission.
     */
    public function store(Request $request): void
    {
        $validator = new WorkspaceValidator();
        $errors    = $validator->validate($request->allPost());

        $slug = trim((string) ($request->post('slug') ?? ''));
        if ($slug !== '') {
            $model = new WorkspaceModel();
            if ($model->slugExists($slug)) {
                $errors['slug'] = "The URL slug '{$slug}' is already taken.";
            }
        }

        if (!empty($errors)) {
            Session::set('errors', $errors);
            Session::set('old_input', $request->allPost());
            $this->redirect('/app/admin/workspaces/create');
            return;
        }

        Session::set('pending_workspace', $request->allPost());
        $this->redirect('/app/admin/workspaces/created');
    }

    /**
     * Step 1.5: Workspace Created Confirmation transitional view.
     */
    public function created(Request $request): void
    {
        if (!Session::has('pending_workspace')) {
            Session::set('errors', ['slug' => 'Session expired. Please restart.']);
            $this->redirect('/app/admin/workspaces/create');
            return;
        }

        $this->render('workspace/created', [
            'title'     => 'Workspace Configured - Step 1.5',
            'workspace' => Session::get('pending_workspace')
        ]);
    }

    /**
     * Step 2: Create Couple Account GET form.
     */
    public function assignOwner(Request $request): void
    {
        if (!Session::has('pending_workspace')) {
            Session::set('errors', ['slug' => 'Session expired. Please restart.']);
            $this->redirect('/app/admin/workspaces/create');
            return;
        }

        $this->render('workspace/assign_owner', [
            'title'  => 'Create Couple Owner - Step 2',
            'old'    => Session::get('old_input') ?? [],
            'errors' => Session::get('errors') ?? []
        ]);
        Session::set('old_input', null);
        Session::set('errors', null);
    }

    /**
     * Step 2: Create Couple Account POST submission.
     */
    public function saveOwner(Request $request): void
    {
        if (!Session::has('pending_workspace')) {
            Session::set('errors', ['slug' => 'Session expired. Please restart.']);
            $this->redirect('/app/admin/workspaces/create');
            return;
        }

        $validator = new WorkspaceValidator();
        $errors = $validator->validateOwner($request->allPost());

        $username = trim((string) ($request->post('username') ?? ''));
        if ($username !== '') {
            $model = new WorkspaceModel();
            if ($model->usernameExists($username)) {
                $errors['username'] = "The username '{$username}' is already taken.";
            }
        }

        if (!empty($errors)) {
            Session::set('errors', $errors);
            Session::set('old_input', $request->allPost());
            $this->redirect('/app/admin/workspaces/create-owner');
            return;
        }

        Session::set('pending_couple', $request->allPost());
        $this->redirect('/app/admin/workspaces/assign-crew');
    }

    /**
     * Step 3: Assign Crew (Optional) GET list.
     */
    public function assignCrew(Request $request): void
    {
        if (!Session::has('pending_workspace') || !Session::has('pending_couple')) {
            Session::set('errors', ['slug' => 'Session expired. Please restart.']);
            $this->redirect('/app/admin/workspaces/create');
            return;
        }

        $db = Database::getConnection();
        $stmt = $db->query('SELECT id, username, display_name, email FROM users WHERE role_id = 3 AND is_active = 1');
        $crews = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $this->render('workspace/assign_crew', [
            'title'  => 'Assign Crew - Step 3',
            'crews'  => $crews,
            'old'    => Session::get('old_input') ?? [],
            'errors' => Session::get('errors') ?? []
        ]);
        Session::set('old_input', null);
        Session::set('errors', null);
    }

    /**
     * Step 3: Assign Crew (Optional) POST submission.
     */
    public function saveCrew(Request $request): void
    {
        if (!Session::has('pending_workspace') || !Session::has('pending_couple')) {
            Session::set('errors', ['slug' => 'Session expired. Please restart.']);
            $this->redirect('/app/admin/workspaces/create');
            return;
        }

        $crewIds = $request->post('crew_ids') ?? [];
        if (!is_array($crewIds)) {
            $crewIds = [];
        }

        Session::set('pending_crew', $crewIds);
        $this->redirect('/app/admin/workspaces/finish');
    }

    /**
     * Step 4: Finish & Review GET screen.
     */
    public function finish(Request $request): void
    {
        if (!Session::has('pending_workspace') || !Session::has('pending_couple')) {
            Session::set('errors', ['slug' => 'Session expired. Please restart.']);
            $this->redirect('/app/admin/workspaces/create');
            return;
        }

        $workspaceData = Session::get('pending_workspace');
        $coupleData    = Session::get('pending_couple');
        $crewIds       = Session::get('pending_crew') ?? [];

        $crewNames = [];
        if (!empty($crewIds)) {
            $db = Database::getConnection();
            $inClause = implode(',', array_map('intval', $crewIds));
            if ($inClause !== '') {
                $stmt = $db->query("SELECT display_name, username FROM users WHERE id IN ($inClause)");
                while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
                    $crewNames[] = $row['display_name'] ?: $row['username'];
                }
            }
        }

        $this->render('workspace/finish', [
            'title'         => 'Review & Finish - Step 4',
            'workspace'     => $workspaceData,
            'couple'        => $coupleData,
            'crewNames'     => $crewNames,
            'errors'        => Session::get('errors') ?? []
        ]);
        Session::set('errors', null);
    }

    /**
     * Step 4: Commit Workspace Creation POST handler.
     */
    public function saveWorkspace(Request $request): void
    {
        if (!Session::has('pending_workspace') || !Session::has('pending_couple')) {
            Session::set('errors', ['slug' => 'Session expired. Please restart.']);
            $this->redirect('/app/admin/workspaces/create');
            return;
        }

        $workspaceData = Session::get('pending_workspace');
        $coupleData    = Session::get('pending_couple');
        $crewIds       = Session::get('pending_crew') ?? [];

        try {
            $adminId   = Session::has('auth_user_id') ? (int) Session::get('auth_user_id') : 0;
            $ipAddress = (string) $request->getIp();

            $service = new WorkspaceService();
            $result  = $service->provision($workspaceData, $coupleData, $crewIds, $adminId, $ipAddress);

            $crewNames = [];
            if (!empty($crewIds)) {
                $db = Database::getConnection();
                $inClause = implode(',', array_map('intval', $crewIds));
                if ($inClause !== '') {
                    $stmt = $db->query("SELECT display_name, username FROM users WHERE id IN ($inClause)");
                    while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) {
                        $crewNames[] = $row['display_name'] ?: $row['username'];
                    }
                }
            }
            $result['crew_names'] = $crewNames;
            $result['workspace_name'] = "{$workspaceData['groom_name']} & {$workspaceData['bride_name']}";
            $result['slug'] = $workspaceData['slug'];
            $result['wedding_date'] = $workspaceData['wedding_date'];

            Session::set('provision_success_result', $result);

            // Clear wizard sessions
            Session::set('pending_workspace', null);
            Session::set('pending_couple', null);
            Session::set('pending_crew', null);

            $this->redirect('/app/admin/workspaces/success');

        } catch (\Throwable $e) {
            Session::set('errors', ['general' => 'Failed to provision workspace: ' . $e->getMessage()]);
            $this->redirect('/app/admin/workspaces/finish');
        }
    }

    /**
     * Success view.
     */
    public function success(Request $request): void
    {
        if (!Session::has('provision_success_result')) {
            $this->redirect('/app/admin/dashboard');
            return;
        }

        $result = Session::get('provision_success_result');
        Session::set('provision_success_result', null); // Clear once loaded

        $this->render('workspace/success', [
            'title'  => 'Workspace Created Successfully',
            'result' => $result
        ]);
    }
}
