<?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', ''));
        }

        Page::create([
            '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),
            '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'),
        ]);

        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'];

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

        Page::updateById($id, [
            '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),
            '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();
        Page::deleteById((int) $params['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++;
        }

        Page::create([
            '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
            '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'),
        ]);

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