<?php

namespace App\Http\Controllers\Admin;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Models\Setting;

/**
 * ITSWEBER CMS – ThemeController
 *
 * Handles theme listing, activation, ZIP-based theme installation, and uninstallation.
 *
 * Security measures for theme upload (Phase 10a):
 *  - File extension + MIME-type validation
 *  - Pre-extraction ZIP-slip check (reject '..' in entry names)
 *  - Post-extraction realpath verification (belt-and-suspenders)
 *  - Slug whitelist regex ([a-z0-9][a-z0-9\-]*)
 *  - theme.json required fields (slug, name, version)
 *  - templates/ directory required
 *  - No write access outside themes/ and public/themes/
 *  - Temp dir always cleaned up (finally block)
 *
 * Security measures for theme uninstallation (Phase 13a):
 *  - CSRF validation
 *  - Slug whitelist validation (prevent path traversal)
 *  - 'default' theme permanently protected
 *  - Active theme cannot be uninstalled
 *  - Theme directory must exist before deletion
 */
class ThemeController extends Controller
{
    // ─────────────────────────────────────────────────────────
    // Public actions
    // ─────────────────────────────────────────────────────────

    public function index(Request $request, array $params = []): void
    {
        $themes           = $this->loadInstalledThemes();
        $activeTheme      = Setting::get('active_theme', 'default');
        $zipOk            = class_exists('ZipArchive');
        $permanentlyProtected = ['default'];

        $this->renderAdmin('themes/index', [
            'pageTitle'            => 'Themes',
            'themes'               => $themes,
            'activeTheme'          => $activeTheme,
            'zipOk'                => $zipOk,
            'permanentlyProtected' => $permanentlyProtected,
            'auth'                 => $this->auth(),
            'csrf'                 => $this->csrf(),
        ]);
    }

    /**
     * POST /admin/themes/uninstall – remove an installed theme.
     *
     * Protection rules:
     *  1. 'default' is permanently protected (system fallback).
     *  2. The currently active theme cannot be uninstalled.
     *  3. Slug must pass whitelist validation (prevents path traversal).
     *  4. Theme directory must exist.
     */
    public function uninstall(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $slug = trim($request->input('theme', ''));

        if (empty($slug)) {
            set_flash('error', 'No theme specified.');
            Response::redirect('/admin/themes');
            return;
        }

        // ── Slug whitelist (belt-and-suspenders against path traversal) ──
        if (!preg_match('/^[a-z0-9][a-z0-9\-]*$/', $slug)) {
            set_flash('error', 'Invalid theme slug.');
            Response::redirect('/admin/themes');
            return;
        }

        // ── Permanently protected themes ─────────────────────────────────
        $permanentlyProtected = ['default'];
        if (in_array($slug, $permanentlyProtected, true)) {
            set_flash('error', 'Theme "' . e($slug) . '" is a system theme and cannot be uninstalled.');
            Response::redirect('/admin/themes');
            return;
        }

        // ── Active theme protection ───────────────────────────────────────
        $activeTheme = Setting::get('active_theme', 'default');
        if ($slug === $activeTheme) {
            set_flash('error', 'The currently active theme cannot be uninstalled. Please activate a different theme first.');
            Response::redirect('/admin/themes');
            return;
        }

        // ── Theme must exist ──────────────────────────────────────────────
        $themeDir = $this->themesBasePath() . '/' . $slug;
        if (!is_dir($themeDir)) {
            set_flash('error', 'Theme "' . e($slug) . '" not found.');
            Response::redirect('/admin/themes');
            return;
        }

        // ── Read theme name for feedback message before deletion ──────────
        $themeName = $slug;
        $jsonFile  = $themeDir . '/theme.json';
        if (is_file($jsonFile)) {
            $meta = json_decode(file_get_contents($jsonFile), true);
            if (is_array($meta) && !empty($meta['name'])) {
                $themeName = $meta['name'];
            }
        }

        // ── Remove themes/{slug}/ ─────────────────────────────────────────
        $this->removeDirectory($themeDir);

        // ── Remove public/themes/{slug}/ if it exists ─────────────────────
        $publicThemeDir = $this->appBasePath() . '/public/themes/' . $slug;
        if (is_dir($publicThemeDir)) {
            $this->removeDirectory($publicThemeDir);
        }

        set_flash('success', 'Theme "' . e($themeName) . '" has been uninstalled.');
        Response::redirect('/admin/themes');
    }

    public function activate(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $slug = trim($request->input('theme', ''));

        if (empty($slug)) {
            set_flash('error', 'No theme specified.');
            Response::redirect('/admin/themes');
            return;
        }

        // Validate: theme directory must exist and contain a theme.json
        $themeDir = $this->themesBasePath() . '/' . $slug;
        if (!is_dir($themeDir) || !is_file($themeDir . '/theme.json')) {
            set_flash('error', 'Theme "' . e($slug) . '" not found or invalid.');
            Response::redirect('/admin/themes');
            return;
        }

        Setting::set('active_theme', $slug, 'branding');
        set_flash('success', 'Theme "' . e($slug) . '" activated. The site now uses this theme.');
        Response::redirect('/admin/themes');
    }

    /**
     * GET /admin/themes/upload – show the theme upload form.
     */
    public function uploadForm(Request $request, array $params = []): void
    {
        $this->renderAdmin('themes/upload', [
            'pageTitle' => 'Install Theme',
            'auth'      => $this->auth(),
            'csrf'      => $this->csrf(),
        ]);
    }

    /**
     * POST /admin/themes/upload – process a theme ZIP upload.
     */
    public function handleUpload(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        // ── 1. File presence ──────────────────────────────────────────────
        if (empty($_FILES['theme_zip']['tmp_name']) || !is_uploaded_file($_FILES['theme_zip']['tmp_name'])) {
            set_flash('error', 'No file uploaded. Please select a theme ZIP file.');
            Response::redirect('/admin/themes/upload');
            return;
        }

        $file = $_FILES['theme_zip'];

        // ── 2. PHP upload error codes ─────────────────────────────────────
        if ($file['error'] !== UPLOAD_ERR_OK) {
            set_flash('error', 'Upload failed: ' . $this->uploadErrorMessage($file['error']));
            Response::redirect('/admin/themes/upload');
            return;
        }

        // ── 3. Size limit (max 10 MB) ─────────────────────────────────────
        $maxBytes = 10 * 1024 * 1024;
        if ($file['size'] > $maxBytes) {
            set_flash('error', 'Theme ZIP exceeds the 10 MB size limit.');
            Response::redirect('/admin/themes/upload');
            return;
        }

        // ── 4. Extension check ────────────────────────────────────────────
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        if ($ext !== 'zip') {
            set_flash('error', 'Only .zip files are accepted as theme packages.');
            Response::redirect('/admin/themes/upload');
            return;
        }

        // ── 5. MIME-type check (fileinfo, belt-and-suspenders) ────────────
        if (class_exists('finfo')) {
            $finfo    = new \finfo(FILEINFO_MIME_TYPE);
            $mimeType = $finfo->file($file['tmp_name']);
            $allowedMime = ['application/zip', 'application/x-zip-compressed', 'application/x-zip'];
            if (!in_array($mimeType, $allowedMime, true)) {
                set_flash('error', 'Uploaded file does not appear to be a valid ZIP archive (MIME: ' . e($mimeType) . ').');
                Response::redirect('/admin/themes/upload');
                return;
            }
        }

        // ── 6. ZipArchive availability ────────────────────────────────────
        if (!class_exists('ZipArchive')) {
            set_flash('error', 'PHP ZipArchive extension is not available on this server. Theme upload is not supported.');
            Response::redirect('/admin/themes/upload');
            return;
        }

        // ── 7. Temp directory ─────────────────────────────────────────────
        $tempDir = sys_get_temp_dir() . '/iw_theme_' . bin2hex(random_bytes(8));
        if (!mkdir($tempDir, 0700, true)) {
            set_flash('error', 'Could not create temporary extraction directory.');
            Response::redirect('/admin/themes/upload');
            return;
        }

        try {
            // ── 8. Open ZIP ───────────────────────────────────────────────
            $zip = new \ZipArchive();
            $openResult = $zip->open($file['tmp_name']);
            if ($openResult !== true) {
                set_flash('error', 'Could not open ZIP archive. The file may be corrupted (ZipArchive error: ' . (int)$openResult . ').');
                Response::redirect('/admin/themes/upload');
                return;
            }

            // ── 9. Pre-extraction ZIP-slip check ──────────────────────────
            for ($i = 0; $i < $zip->numFiles; $i++) {
                $entryName = $zip->getNameIndex($i);
                if ($entryName === false) {
                    continue;
                }
                // Reject any entry with parent-directory traversal or null bytes
                if (strpos($entryName, '..') !== false || strpos($entryName, "\0") !== false) {
                    $zip->close();
                    set_flash('error', 'Security: Theme ZIP contains unsafe path entries (path traversal detected). Installation aborted.');
                    Response::redirect('/admin/themes/upload');
                    return;
                }
                // Reject absolute paths
                if (substr($entryName, 0, 1) === '/' || (strlen($entryName) > 1 && $entryName[1] === ':')) {
                    $zip->close();
                    set_flash('error', 'Security: Theme ZIP contains absolute path entries. Installation aborted.');
                    Response::redirect('/admin/themes/upload');
                    return;
                }
            }

            // ── 10. Extract ───────────────────────────────────────────────
            if (!$zip->extractTo($tempDir)) {
                $zip->close();
                set_flash('error', 'Failed to extract ZIP archive. The file may be corrupted or the server lacks write permissions.');
                Response::redirect('/admin/themes/upload');
                return;
            }
            $zip->close();

            // ── 11. Post-extraction realpath verification (belt-and-suspenders)
            $realTempBase = realpath($tempDir);
            if ($realTempBase === false) {
                set_flash('error', 'Security: Could not resolve temp directory path after extraction.');
                Response::redirect('/admin/themes/upload');
                return;
            }
            $realTempBase .= DIRECTORY_SEPARATOR;

            foreach ($this->recursiveFileList($tempDir) as $extractedFile) {
                $realExtracted = realpath($extractedFile);
                if ($realExtracted === false || strpos($realExtracted, $realTempBase) !== 0) {
                    set_flash('error', 'Security: ZIP-slip path escape detected after extraction. Installation aborted.');
                    Response::redirect('/admin/themes/upload');
                    return;
                }
            }

            // ── 12. Locate theme.json (flat or one-level-wrapped) ─────────
            $themeRoot = $this->findThemeRoot($tempDir);
            if ($themeRoot === null) {
                set_flash('error', 'Invalid theme package: no theme.json found. The ZIP must contain a theme.json at the root or inside a single subdirectory.');
                Response::redirect('/admin/themes/upload');
                return;
            }

            // ── 13. Parse and validate theme.json ─────────────────────────
            $rawJson   = file_get_contents($themeRoot . '/theme.json');
            $themeJson = json_decode($rawJson, true);

            if (!is_array($themeJson)) {
                set_flash('error', 'Invalid theme package: theme.json is not valid JSON.');
                Response::redirect('/admin/themes/upload');
                return;
            }

            $slug    = trim($themeJson['slug']    ?? '');
            $name    = trim($themeJson['name']    ?? '');
            $version = trim($themeJson['version'] ?? '');

            if ($slug === '' || $name === '' || $version === '') {
                set_flash('error', 'Invalid theme package: theme.json must contain "slug", "name", and "version" fields.');
                Response::redirect('/admin/themes/upload');
                return;
            }

            // ── 14. Slug whitelist validation ─────────────────────────────
            if (!preg_match('/^[a-z0-9][a-z0-9\-]*$/', $slug)) {
                set_flash('error', 'Invalid theme slug "' . e($slug) . '". Slug must start with a lowercase letter or digit and contain only lowercase letters, digits, and hyphens.');
                Response::redirect('/admin/themes/upload');
                return;
            }

            // ── 15. templates/ directory required ─────────────────────────
            if (!is_dir($themeRoot . '/templates')) {
                set_flash('error', 'Invalid theme package: a templates/ directory is required.');
                Response::redirect('/admin/themes/upload');
                return;
            }

            // ── 16. Target path determination ─────────────────────────────
            $basePath       = $this->appBasePath();
            $themeTargetDir = $basePath . '/themes/' . $slug;
            $publicThemeDir = $basePath . '/public/themes/' . $slug;

            // ── 17. Protect core themes from accidental overwrite ─────────
            $protectedSlugs = ['default'];
            if (in_array($slug, $protectedSlugs, true)) {
                set_flash('error', 'The theme slug "' . e($slug) . '" is reserved and cannot be overwritten by upload.');
                Response::redirect('/admin/themes/upload');
                return;
            }

            // ── 18. Copy theme to themes/{slug}/ ──────────────────────────
            $this->copyDirectory($themeRoot, $themeTargetDir);

            // ── 19. Mirror assets to public/themes/{slug}/assets/ ─────────
            $sourceAssetsDir = $themeTargetDir . '/assets';
            if (is_dir($sourceAssetsDir)) {
                $publicAssetsDir = $publicThemeDir . '/assets';
                $this->copyDirectory($sourceAssetsDir, $publicAssetsDir);
            }

            // ── 20. Success ───────────────────────────────────────────────
            $isUpdate = is_dir($themeTargetDir) && count(glob($themeTargetDir . '/*')) > 0;
            $action   = isset($isUpdate) ? 'updated' : 'installed';
            set_flash('success',
                'Theme "' . e($name) . '" v' . e($version) . ' ' . $action . ' successfully. '
                . 'You can now activate it below.'
            );
            Response::redirect('/admin/themes');

        } finally {
            // ── 21. Always remove temp dir ────────────────────────────────
            $this->removeDirectory($tempDir);
        }
    }

    // ─────────────────────────────────────────────────────────
    // Private helpers
    // ─────────────────────────────────────────────────────────

    /**
     * Absolute path to the project root (4 levels up from Admin/ThemeController.php).
     */
    private function appBasePath(): string
    {
        return dirname(__DIR__, 4);
    }

    /**
     * Absolute path to the themes/ directory.
     */
    private function themesBasePath(): string
    {
        return $this->appBasePath() . '/themes';
    }

    /**
     * Scan the themes/ directory and return metadata for all installed themes.
     */
    private function loadInstalledThemes(): array
    {
        $base   = $this->themesBasePath();
        $themes = [];

        foreach (glob($base . '/*', GLOB_ONLYDIR) as $dir) {
            $slug     = basename($dir);
            $jsonFile = $dir . '/theme.json';

            if (!is_file($jsonFile)) {
                continue;
            }

            $raw  = file_get_contents($jsonFile);
            $meta = json_decode($raw, true);

            if (!is_array($meta)) {
                continue;
            }

            // Resolve thumbnail URL: only expose if file is mirrored to public/
            $thumbnailRelative = $meta['thumbnail'] ?? null;
            $thumbnailUrl      = null;
            if ($thumbnailRelative !== null) {
                $publicThumbPath = $this->appBasePath()
                    . '/public/themes/' . $slug . '/'
                    . ltrim(str_replace('\\', '/', $thumbnailRelative), '/');
                if (is_file($publicThumbPath)) {
                    $thumbnailUrl = '/themes/' . $slug . '/'
                        . ltrim(str_replace('\\', '/', $thumbnailRelative), '/');
                }
            }

            $themes[$slug] = [
                'slug'         => $slug,
                'name'         => $meta['name']        ?? ucfirst($slug),
                'description'  => $meta['description'] ?? '',
                'version'      => $meta['version']     ?? '1.0.0',
                'author'       => $meta['author']      ?? '',
                'thumbnail'    => $meta['thumbnail']   ?? null,
                'thumbnailUrl' => $thumbnailUrl,
                'colors'       => $meta['colors']      ?? [],
            ];
        }

        ksort($themes);
        return $themes;
    }

    /**
     * Find the directory containing theme.json.
     * Supports flat layout (theme.json at root of temp dir) and
     * single-subdirectory wrapped layout (e.g. user zipped a folder).
     */
    private function findThemeRoot(string $tempDir): ?string
    {
        // Flat: theme.json at tempDir root
        if (is_file($tempDir . '/theme.json')) {
            return $tempDir;
        }

        // One-level-wrapped: theme.json inside a single subdirectory
        $subdirs = glob($tempDir . '/*', GLOB_ONLYDIR);
        if ($subdirs !== false && count($subdirs) === 1) {
            $subDir = $subdirs[0];
            if (is_file($subDir . '/theme.json')) {
                return $subDir;
            }
        }

        return null;
    }

    /**
     * Recursively copy a directory.
     */
    private function copyDirectory(string $src, string $dst): void
    {
        if (!is_dir($dst)) {
            mkdir($dst, 0755, true);
        }

        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($src, \RecursiveDirectoryIterator::SKIP_DOTS),
            \RecursiveIteratorIterator::SELF_FIRST
        );

        foreach ($iterator as $item) {
            $relative = substr($item->getPathname(), strlen($src));
            $target   = $dst . $relative;

            if ($item->isDir()) {
                if (!is_dir($target)) {
                    mkdir($target, 0755, true);
                }
            } else {
                copy($item->getPathname(), $target);
            }
        }
    }

    /**
     * Recursively remove a directory.
     */
    private function removeDirectory(string $dir): void
    {
        if (!is_dir($dir)) {
            return;
        }

        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS),
            \RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($iterator as $item) {
            if ($item->isDir()) {
                rmdir($item->getPathname());
            } else {
                unlink($item->getPathname());
            }
        }

        rmdir($dir);
    }

    /**
     * List all files under a directory recursively.
     */
    private function recursiveFileList(string $dir): array
    {
        $files    = [];
        $iterator = new \RecursiveIteratorIterator(
            new \RecursiveDirectoryIterator($dir, \RecursiveDirectoryIterator::SKIP_DOTS)
        );

        foreach ($iterator as $item) {
            if ($item->isFile()) {
                $files[] = $item->getPathname();
            }
        }

        return $files;
    }

    /**
     * Human-readable PHP upload error message.
     */
    private function uploadErrorMessage(int $code): string
    {
        return match ($code) {
            UPLOAD_ERR_INI_SIZE   => 'The file exceeds the server\'s upload_max_filesize limit.',
            UPLOAD_ERR_FORM_SIZE  => 'The file exceeds the MAX_FILE_SIZE limit specified in the form.',
            UPLOAD_ERR_PARTIAL    => 'The file was only partially uploaded. Please try again.',
            UPLOAD_ERR_NO_FILE    => 'No file was uploaded.',
            UPLOAD_ERR_NO_TMP_DIR => 'Missing temporary upload directory on the server.',
            UPLOAD_ERR_CANT_WRITE => 'Failed to write the file to disk. Check server permissions.',
            UPLOAD_ERR_EXTENSION  => 'A PHP extension stopped the upload.',
            default               => 'Unknown upload error (code ' . $code . ').',
        };
    }
}
