<?php

namespace App\Http\Controllers\Admin;

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

class RevisionController extends Controller
{
    /**
     * List revisions for a content item (JSON response for modal).
     */
    public function list(Request $request, array $params = []): void
    {
        $type = $params['type'] ?? '';
        $id   = (int) ($params['id'] ?? 0);

        if (!in_array($type, ['page', 'blog_post'], true) || $id <= 0) {
            Response::json(['ok' => false, 'error' => 'invalid']);
            return;
        }

        $revisions = ContentRevision::forContent($type, $id);

        // Build lightweight list (no full snapshots)
        $list = [];
        foreach ($revisions as $rev) {
            $list[] = [
                'id'         => (int) $rev['id'],
                'title'      => $rev['title'] ?? '',
                'changed_by' => $rev['changed_by_name'] ?? 'System',
                'created_at' => $rev['created_at'],
            ];
        }

        Response::json(['ok' => true, 'revisions' => $list, 'total' => count($list)]);
    }

    /**
     * View a single revision with diff data (JSON).
     */
    public function view(Request $request, array $params = []): void
    {
        $revId = (int) ($params['revId'] ?? 0);
        $rev   = ContentRevision::findWithSnapshot($revId);

        if (!$rev) {
            Response::json(['ok' => false, 'error' => 'not_found']);
            return;
        }

        // Load current state for comparison
        $current = null;
        if ($rev['content_type'] === 'page') {
            $current = Page::find((int) $rev['content_id']);
        } elseif ($rev['content_type'] === 'blog_post') {
            $current = BlogPost::find((int) $rev['content_id']);
        }

        // Build diff: compare snapshot fields to current
        $snapshot = $rev['snapshot_data'] ?? [];
        $diff = [];
        $compareFields = ['title', 'slug', 'content', 'excerpt', 'status', 'template',
                          'seo_title', 'seo_description', 'og_image', 'robots_meta',
                          'canonical_url', 'custom_css', 'custom_js', 'featured_image'];

        foreach ($compareFields as $field) {
            $oldVal = $snapshot[$field] ?? null;
            $newVal = $current[$field] ?? null;

            if ($oldVal !== $newVal && ($oldVal !== null || $newVal !== null)) {
                $diff[$field] = [
                    'old' => $oldVal ?? '',
                    'new' => $newVal ?? '',
                ];
            }
        }

        Response::json([
            'ok'         => true,
            'revision'   => [
                'id'         => (int) $rev['id'],
                'title'      => $rev['title'],
                'created_at' => $rev['created_at'],
                'changed_by' => $rev['changed_by'],
            ],
            'diff'       => $diff,
            'field_count' => count($diff),
        ]);
    }

    /**
     * Restore a revision – replaces current content with snapshot.
     */
    public function restore(Request $request, array $params = []): void
    {
        $this->validateCsrf();

        $revId = (int) ($params['revId'] ?? 0);
        $rev   = ContentRevision::findWithSnapshot($revId);

        if (!$rev || empty($rev['snapshot_data'])) {
            Response::json(['ok' => false, 'error' => 'not_found']);
            return;
        }

        $snapshot = $rev['snapshot_data'];
        $type     = $rev['content_type'];
        $cid      = (int) $rev['content_id'];

        // Store current state as a revision before restoring
        if ($type === 'page') {
            $current = Page::find($cid);
            if ($current) {
                ContentRevision::store('page', $cid, $current, $this->auth()->userId());

                // Restore only content fields, not system fields like id, created_at
                $restoreFields = ['title', 'slug', 'content', 'template', 'status',
                                  'sort_order', 'is_homepage', 'show_title',
                                  'seo_title', 'seo_description', 'og_image',
                                  'robots_meta', 'canonical_url', 'custom_css', 'custom_js'];

                $data = [];
                foreach ($restoreFields as $f) {
                    if (array_key_exists($f, $snapshot)) {
                        $data[$f] = $snapshot[$f];
                    }
                }
                $data['updated_at'] = date('Y-m-d H:i:s');

                Page::updateById($cid, $data);
            }
        } elseif ($type === 'blog_post') {
            $current = BlogPost::find($cid);
            if ($current) {
                ContentRevision::store('blog_post', $cid, $current, $this->auth()->userId());

                $restoreFields = ['title', 'slug', 'content', 'excerpt', 'status',
                                  'category_id', 'featured_image', 'published_at',
                                  'seo_title', 'seo_description', 'og_image',
                                  'robots_meta', 'canonical_url', 'custom_css', 'custom_js'];

                $data = [];
                foreach ($restoreFields as $f) {
                    if (array_key_exists($f, $snapshot)) {
                        $data[$f] = $snapshot[$f];
                    }
                }
                $data['updated_at'] = date('Y-m-d H:i:s');

                BlogPost::updateById($cid, $data);
            }
        }

        Response::json(['ok' => true]);
    }
}
