<?php

declare(strict_types=1);

namespace PpPhp\Modules\VersionHistory\Controllers;

use PpPhp\Core\Config;
use PpPhp\Core\DB;
use PpPhp\Core\Security;
use PpPhp\Core\VersionHistory;

/**
 * JSON endpoints for the Version History panel: list saved versions, save a
 * new one on demand, bring one back, or remove one.
 */
class VersionHistoryController
{
    private array $project = [];

    public function __construct(private Config $config) {}

    public function list(string $slug): void
    {
        header('Content-Type: application/json');
        $this->initProject($slug);
        echo json_encode([
            'success'  => true,
            'versions' => VersionHistory::list($slug),
            'count'    => VersionHistory::count($slug),
        ]);
        exit;
    }

    public function create(string $slug): void
    {
        header('Content-Type: application/json');
        $this->initProject($slug);
        $input = json_decode((string) file_get_contents('php://input'), true) ?: [];
        $note  = trim((string) ($input['note'] ?? ''));
        $meta  = VersionHistory::snapshot($slug, $note !== '' ? $note : 'Checkpoint', 'checkpoint');
        echo json_encode([
            'success' => $meta !== null,
            'version' => $meta,
            'message' => $meta !== null ? 'Version saved.' : 'There is nothing new to save yet.',
        ]);
        exit;
    }

    public function restore(string $slug): void
    {
        header('Content-Type: application/json');
        $this->initProject($slug);
        $input = json_decode((string) file_get_contents('php://input'), true) ?: [];
        $ok = VersionHistory::restore($slug, (string) ($input['id'] ?? ''));
        echo json_encode([
            'success' => $ok,
            'message' => $ok ? 'Your site has been brought back to this version.' : 'That version could not be found.',
        ]);
        exit;
    }

    public function delete(string $slug): void
    {
        header('Content-Type: application/json');
        $this->initProject($slug);
        $input = json_decode((string) file_get_contents('php://input'), true) ?: [];
        VersionHistory::delete($slug, (string) ($input['id'] ?? ''));
        echo json_encode(['success' => true]);
        exit;
    }

    private function initProject(string $slug): void
    {
        Security::RequireAuth();
        DB::Init();
        $project = DB::Select('projects', ['slug' => $slug, 'created_by' => Security::CurrentUserData()['id']]);
        if (empty($project) && Security::IsAdmin()) {
            $project = DB::Select('projects', ['slug' => $slug]);
        }
        if (empty($project)) {
            http_response_code(404);
            echo json_encode(['success' => false, 'message' => 'Project not found.']);
            exit;
        }
        $this->project = $project[0];
    }
}
