<?php

declare(strict_types=1);

namespace PpPhp\Modules\Settings\Controllers;

use PpPhp\Core\Auth\OwnerVerification;
use PpPhp\Core\Config;
use PpPhp\Core\Security;

/**
 * Establish the platform owner — the ONLY way to create the reserved
 * `admin-ppradhan` owner account, gated by an email code sent to the fixed
 * owner mailbox. Reachable by any signed-in administrator, but only whoever
 * controls that mailbox can complete it. Once an owner is established (or
 * grandfathered), this page just reports that.
 */
class OwnerSetupController
{
    public function __construct(private Config $config) {}

    private function gate(): void
    {
        Security::RequireAuth();
        if (!Security::IsAdmin()) {
            redirect('/projects');
        }
    }

    private function json(array $payload, int $code = 200): void
    {
        http_response_code($code);
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode($payload);
    }

    public function index(): string
    {
        $this->gate();
        $baseUrl   = $this->config->get('base_url');
        $assetsUrl = $this->config->get('assets_url');
        $token     = Security::CSRF()->Token();
        $verified  = OwnerVerification::isVerified();
        $pending   = OwnerVerification::challengePending();
        $ownerUser = Security::ownerUsername();

        ob_start();
        include __DIR__ . '/../Views/owner_setup.php';
        return (string) ob_get_clean();
    }

    public function send(): void
    {
        $this->gate();
        if (!Security::CSRF()->Check((string) ($_POST['_token'] ?? ''))) {
            $this->json(['success' => false, 'message' => 'Your security token expired. Reload the page.'], 400);
            return;
        }
        $this->json(OwnerVerification::sendChallenge());
    }

    public function verify(): void
    {
        $this->gate();
        $in = json_decode((string) file_get_contents('php://input'), true) ?: $_POST;
        if (!Security::CSRF()->Check((string) ($in['_token'] ?? ''))) {
            $this->json(['success' => false, 'message' => 'Your security token expired. Reload the page.'], 400);
            return;
        }
        $code = (string) ($in['code'] ?? '');
        $pass = (string) ($in['password'] ?? '');
        $this->json(OwnerVerification::verify($code, $pass));
    }
}
