<?php

namespace App\Http\Controllers\Admin;

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

class PageController extends Controller
{
    public function index(Request $request, array $params = []): void
    {
        $pages = Page::all('sort_order', 'ASC');
        $view = $this->app->service('view');
        $html = $view->renderAdmin('pages/index', [
            'pageTitle' => 'Pages',
            'pages'     => $pages,
            'auth'      => $this->auth(),
            'csrf'      => $this->csrf(),
        ]);
        Response::html($html);
    }

    public function create(Request $request, array $params = []): void
    {
        $view = $this->app->service('view');
        $html = $view->renderAdmin('pages/form', [
            'pageTitle' => 'Create Page',
            'page'      => null,
            'auth'      => $this->auth(),
            'csrf'      => $this->csrf(),
        ]);
        Response::html($html);
    }

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

        $slug = trim($request->input('slug', ''));
        if (empty($slug)) {
            $slug = slugify($request->input('title', ''));
        }

        $data = [
            'title'           => trim($request->input('title', '')),
            'slug'            => $slug,
            'content'         => $request->input('content', ''),
            'template'        => $request->input('template', 'page'),
            'status'          => $request->input('status', 'draft'),
            'sort_order'      => (int) $request->input('sort_order', 0),
            'is_homepage'     => (int) $request->input('is_homepage', 0),
            'show_title'      => (int) $request->input('show_title', 1),
            'seo_title'       => trim($request->input('seo_title', '')),
            'seo_description' => trim($request->input('seo_description', '')),
            'created_by'      => $this->auth()->userId(),
            'created_at'      => date('Y-m-d H:i:s'),
            'updated_at'      => date('Y-m-d H:i:s'),
        ];

        // Include page_type only if the column exists (migration 021)
        if (self::hasPageTypeColumn()) {
            $data['page_type'] = 'page';
        }

        Page::create($data);

        set_flash('success', __('messages.page_created', ['title' => $slug]));
        Response::redirect('/admin/pages');
    }

    public function edit(Request $request, array $params = []): void
    {
        $page = Page::find((int) $params['id']);
        if (!$page) {
            Response::redirect('/admin/pages');
            return;
        }

        $view = $this->app->service('view');
        $html = $view->renderAdmin('pages/form', [
            'pageTitle' => 'Edit Page',
            'page'      => $page,
            'auth'      => $this->auth(),
            'csrf'      => $this->csrf(),
        ]);
        Response::html($html);
    }

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

        $existing = Page::find($id);
        if (!$existing) {
            Response::redirect('/admin/pages');
            return;
        }

        $isSystem = Page::isSystemPage($existing);

        // For system pages, preserve slug and template
        if ($isSystem) {
            $slug     = $existing['slug'];
            $template = $existing['template'];
        } else {
            $slug = trim($request->input('slug', ''));
            if (empty($slug)) {
                $slug = slugify($request->input('title', ''));
            }
            $template = $request->input('template', 'page');
        }

        Page::updateById($id, [
            'title'           => trim($request->input('title', '')),
            'slug'            => $slug,
            'content'         => $request->input('content', ''),
            'template'        => $template,
            'status'          => $request->input('status', 'draft'),
            'sort_order'      => (int) $request->input('sort_order', 0),
            'is_homepage'     => $isSystem ? (int) $existing['is_homepage'] : (int) $request->input('is_homepage', 0),
            'show_title'      => (int) $request->input('show_title', 1),
            'seo_title'       => trim($request->input('seo_title', '')),
            'seo_description' => trim($request->input('seo_description', '')),
            'updated_at'      => date('Y-m-d H:i:s'),
        ]);

        set_flash('success', __('messages.page_updated'));
        Response::redirect('/admin/pages');
    }

    public function delete(Request $request, array $params = []): void
    {
        $this->validateCsrf();
        $id   = (int) $params['id'];
        $page = Page::find($id);

        // Prevent deletion of system/module pages
        if ($page && Page::isSystemPage($page)) {
            set_flash('error', __('messages.system_page_delete_error'));
            Response::redirect('/admin/pages');
            return;
        }

        Page::deleteById($id);
        set_flash('success', __('messages.page_deleted'));
        Response::redirect('/admin/pages');
    }

    // -------------------------------------------------------------------------
    // CLONE / DUPLICATE
    // -------------------------------------------------------------------------

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

        $id       = (int) $params['id'];
        $original = Page::find($id);

        if (!$original) {
            set_flash('error', __('messages.not_found', ['item' => 'Page']));
            Response::redirect('/admin/pages');
            return;
        }

        // Generate a unique slug: {slug}-copy, {slug}-copy-2, ...
        $baseSlug = $original['slug'] . '-copy';
        $newSlug  = $baseSlug;
        $counter  = 2;
        while (Page::findBySlug($newSlug)) {
            $newSlug = $baseSlug . '-' . $counter;
            $counter++;
        }

        $cloneData = [
            'title'           => 'Copy of ' . $original['title'],
            'slug'            => $newSlug,
            'content'         => $original['content'],
            'template'        => $original['template'],
            'status'          => 'draft',
            'sort_order'      => (int) $original['sort_order'],
            'is_homepage'     => 0,         // never carry over homepage flag
            'show_title'      => (int) ($original['show_title'] ?? 1),
            'seo_title'       => $original['seo_title'],
            'seo_description' => $original['seo_description'],
            'created_by'      => $this->auth()->userId(),
            'created_at'      => date('Y-m-d H:i:s'),
            'updated_at'      => date('Y-m-d H:i:s'),
        ];

        // Include page_type only if the column exists (migration 021)
        if (self::hasPageTypeColumn()) {
            $cloneData['page_type'] = 'page';  // clones are always normal pages
        }

        Page::create($cloneData);

        set_flash('success', __('messages.page_duplicated'));
        Response::redirect('/admin/pages');
    }

    // -------------------------------------------------------------------------
    // HELPERS
    // -------------------------------------------------------------------------

    /**
     * Check whether the page_type column exists in iw_pages (migration 021).
     * Cached per-request to avoid repeated SHOW COLUMNS queries.
     */
    private static function hasPageTypeColumn(): bool
    {
        static $exists = null;
        if ($exists === null) {
            try {
                $cols = \App\Core\App::getInstance()->db()->fetchAll(
                    "SHOW COLUMNS FROM iw_pages LIKE 'page_type'"
                );
                $exists = !empty($cols);
            } catch (\Exception $e) {
                $exists = false;
            }
        }
        return $exists;
    }
}
