<?php

namespace App\Livewire\Admin;

use Livewire\Component;
use Livewire\WithPagination;
use App\Models\{CryptoNewsModel, AuthorModel, Channel, commonSEO, commonSlug};
use App\Models\CryptoNewsDraft;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use App\Http\Requests\CryptoNews\StoreCryptoNewsRequest;
use App\Rules\WordsBetween;
use App\Rules\WebsiteInterlink;
use App\Rules\ExternalLink;
use App\Rules\FocusKeywordDensity;
use App\Rules\KeywordDensity;
use App\Services\PermissionService;
use App\Helpers\CommonHelper;
use App\Rules\NoDuplicateKeywordsRule;
use App\Rules\DescriptionContentRule;
use App\Rules\TitlePixelWidth;
use App\Services\FocusKeywordFieldsValidator;
use App\Livewire\Traits\WithDelete;
use Carbon\Carbon;
use App\Livewire\Traits\WithActiveDeactive;
use Illuminate\Support\Facades\Schema;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Illuminate\Support\Facades\Artisan;

class CryptoNews extends Component
{
    use WithPagination;
    use WithFileUploads;
    use WithDelete;
    use WithActiveDeactive;

    public $perPage = 20;
    public $updateMode = false;
    public $viewMode = false;
    public $formMode = false;
    public $cryptoToView;
    public $search = '';
    public $month = '';
    public $language;
    public $channel;
    public $idToEdit;
    public $author_id;
    public $author_name;
    public $author;
    public $user_id;
    public $is_gabbar;
    public $is_review;
    public $is_featured;
    public $channel_id = 1;
    public $created_by;
    public $is_home;
    public $title;
    public $alias;
    public $interlink_url;
    public $h1_title;
    public $h2_title;
    public $short_desc;
    public $description;
    public $url;
    public $image;
    public $oldImage;
    public $img_alt_title;
    public $is_thumb = 0;
    public $urlToImage;
    public $word_file;
    public $tags;
    public $is_active = 1;
    public $is_guest;
    public $is_rss_feed;
    public $is_paid;
    public $is_organic;
    public $is_cryptotax;
    public $is_seo_check;
    public $publishedAt;
    public $focus_keyword;
    public $seo_title;
    public $meta_keywords;
    public $meta_description;
    public $likes_counts;
    public $article;
    public $breadcrumbs;
    public $course_info;
    public $data_set;
    public $discussion_forum;
    public $events;
    public $faq;
    public $image_metadata;
    public $project_name;
    public $project_website;
    public $project_id;
    public $new_article;
    public $paywalled_content;
    public $product;
    public $profile;
    public $organization;
    public $review_snippets;
    public $sitelinks;
    public $video;
    public $dynamic_rss_feed;
    public $dataset_level;
    public $dataset_json;
    public $update_status;
    public $faqs;
    public $status;
    public $prompt_instructions;
    // ── Draft ──────────────────────────────────────────────────────────────
    public $draftId = null;
    public $draftSavedAt = null;
    // ───────────────────────────────────────────────────────────────────────
    protected $paginationTheme = 'bootstrap';
    public $permissions = [];
    public $role_id;
    public $startDatePublish;
    public $endDatePublish;
    public $startDateCreated;
    public $endDateCreated;

    // Listen for JS-triggered draft save (Alpine calls this every 2 minutes)
    protected $listeners = [
        'triggerDraftSave' => 'saveDraft',
    ];

    // MOUNT

    public function mount()
    {
        $permissionService = app(PermissionService::class);
        $data = $permissionService->getUserPermissions();

        $this->permissions = $data['permissions'];
        $this->role_id = $data['role_id'];

        if (!in_array(22, $this->permissions) && $this->role_id != 1) {
            session()->flash('error', 'You do not have permission to access News List.');
            return redirect()->route('admin.dashboard');
        }

        // CUSTOM RULE: MAX KEYWORD DENSITY
        Validator::extend('max_keyword_density', function ($attribute, $value, $parameters) {
            $focus = $this->focus_keyword;
            if (!$focus || !$value)
                return true;

            $clean = strip_tags($value);
            $totalWords = str_word_count($clean);
            if ($totalWords === 0)
                return true;

            $keywordCount = substr_count(strtolower($clean), strtolower($focus));
            $density = ($keywordCount / $totalWords) * 100;

            return $density <= $parameters[0];
        });

        // CUSTOM RULE: NO DUPLICATE KEYWORDS
        Validator::extend('no_duplicate_keywords', function ($attribute, $value) {
            if (!$value)
                return true;
            $keywords = array_map('trim', explode(',', strtolower($value)));
            return count($keywords) === count(array_unique($keywords));
        });
    }

    // =========================================================================
    // DRAFT — OPEN CREATE FORM
    // =========================================================================
    public function openCreateForm()
    {
        $this->formMode = true;

        $draft = CryptoNewsDraft::where('user_id', Auth::id())
            ->latest()
            ->first();

        if ($draft) {
            $this->dispatch(
                'promptDraftRestore',
                draftId: $draft->id,
                savedAt: $draft->updated_at->format('d M Y, h:i A'),
                draftData: $draft->toArray(),
            );
        }
    }

    // =========================================================================
    // DRAFT — SAVE (called every 2 min by Alpine JS in create mode)
    // =========================================================================

    public function saveDraft(): void
    {
        // Never save drafts in edit mode or when the form is closed
        if ($this->updateMode || !$this->formMode) {
            return;
        }

        $userId = Auth::check() ? Auth::id() : 1;

        $payload = [
            'user_id' => $userId,
            'author_id' => $this->author_id ?? null,
            'author_name' => $this->author_name ?? null,
            'is_gabbar' => $this->is_gabbar ?? null,
            'is_featured' => $this->is_featured ?? 0,
            'channel_id' => $this->channel_id ?? 1,
            // 'is_home'          => $this->is_home          ?? 0,
            'title' => $this->title ?? null,
            'alias' => $this->alias ?? null,
            'h1_title' => $this->h1_title ?? null,
            'h2_title' => $this->h2_title ?? null,
            'short_desc' => $this->short_desc ?? null,
            'description' => $this->description ?? null,
            'url' => $this->url ?? null,
            'img_alt_title' => $this->img_alt_title ?? null,
            'urlToImage' => $this->urlToImage ?? null,
            'tags' => $this->tags ?? null,
            'status' => $this->status ?? null,
            'is_rss_feed' => $this->is_rss_feed ?? 0,
            'is_paid' => $this->is_paid ?? 0,
            'is_organic' => $this->is_organic ?? 0,
            'is_cryptotax' => $this->is_cryptotax ?? 0,
            'publishedAt' => $this->publishedAt
                ? strtotime($this->publishedAt)
                : time(),
            'focus_keyword' => $this->focus_keyword ?? null,
            'seo_title' => $this->seo_title ?? null,
            'meta_keywords' => $this->meta_keywords ?? null,
            'meta_description' => $this->meta_description ?? null,
            'faq' => $this->faq ?? null,
            'project_name' => $this->project_name ?? null,
            'project_website' => $this->project_website ?? null,
            'project_id' => $this->project_id ?? null,
            'image_metadata' => $this->image_metadata,
            'article' => $this->article,
            'new_article' => $this->new_article,
            'discussion_forum' => $this->discussion_forum,
            'paywalled_content' => $this->paywalled_content,
            'profile' => $this->profile,
            'organization' => $this->organization,
            'review_snippets' => $this->review_snippets,
            'is_review' => $this->is_review ?? 0,
            'sitelinks' => $this->sitelinks,
            'video' => $this->video,
            'dynamic_rss_feed' => $this->dynamic_rss_feed,
            'breadcrumbs' => $this->breadcrumbs,
            'prompt_instructions' => $this->prompt_instructions
        ];

        // updateOrCreate: passing id=0 forces an INSERT on the very first save
        $draft = CryptoNewsDraft::updateOrCreate(
            ['alias' => $this->alias, 'user_id' => $userId],
            $payload
        );

        $this->draftId = $draft->id;
        $this->draftSavedAt = now()->format('h:i A');

        // Tell Alpine to update the "saved at" indicator
        $this->dispatch('onDraftSaved', savedAt: $this->draftSavedAt);
    }

    // =========================================================================
    // DRAFT — RESUME (user clicked "Yes" on the restore prompt)
    // =========================================================================

    public function resumeDraft(int $draftId): void
    {
        $draft = CryptoNewsDraft::where('id', $draftId)
            ->where('user_id', Auth::id())
            ->first();

        if (!$draft)
            return;

        $fields = [
            'author_id',
            'author_name',
            'is_gabbar',
            'is_featured',
            'channel_id',
            'is_home',
            'title',
            'alias',
            'h1_title',
            'h2_title',
            'short_desc',
            'description',
            'url',
            'img_alt_title',
            'urlToImage',
            'tags',
            'status',
            'is_rss_feed',
            'is_paid',
            'is_organic',
            'is_cryptotax',
            'focus_keyword',
            'seo_title',
            'meta_keywords',
            'meta_description',
            'faq',
            'project_name',
            'project_website',
            'project_id',
            'image_metadata',
            'article',
            'new_article',
            'discussion_forum',
            'breadcrumbs',
            'paywalled_content',
            'profile',
            'organization',
            'review_snippets',
            'is_review',
            'sitelinks',
            'video',
            'dynamic_rss_feed',
            'prompt_instructions'
        ];

        foreach ($fields as $field) {
            if (!is_null($draft->$field)) {
                $this->$field = $draft->$field;
            }
        }

        // publishedAt is stored as unix timestamp — convert back for datetime-local input
        if ($draft->publishedAt) {
            $this->publishedAt = date('Y-m-d\TH:i', $draft->publishedAt);
        }

        $this->draftId = $draft->id;
        $this->draftSavedAt = $draft->updated_at->format('h:i A');

        // Reload CKEditor with the saved description
        if (!empty($this->description)) {
            $this->dispatch('load-editor', content: $this->description);
        }
    }

    // =========================================================================
    // DRAFT — DISCARD
    // =========================================================================

    public function discardDraft(): void
    {
        if ($this->draftId) {
            CryptoNewsDraft::where('id', $this->draftId)
                ->where('user_id', Auth::id())
                ->delete();
        }

        $this->draftId = null;
        $this->draftSavedAt = null;

        $this->dispatch('onDraftDiscarded');
    }

    public function validateExtraSeoRules()
    {
        $focus = $this->focus_keyword;

        if (!$focus)
            return;

        $focusLower = strtolower($focus);

        if ($this->title) {
            $lowerTitle = strtolower($this->title);

            if (stripos($lowerTitle, $focusLower) === false) {
                $this->addError('title', 'The title must contain the focus keyword.');
            }

            if (substr_count($lowerTitle, $focusLower) > 1) {
                $this->addError('title', 'The title must contain the focus keyword only once.');
            }
        }

        if ($this->meta_description && stripos($this->meta_description, $focusLower) === false) {
            $this->addError('meta_description', 'The meta description must contain the focus keyword.');
        }

        // if ($this->meta_keywords && stripos($this->meta_keywords, $focusLower) === false) {
        //     $this->addError('meta_keywords', 'The meta keywords must contain the focus keyword.');
        // }

        if ($this->seo_title && stripos($this->seo_title, $focusLower) === false) {
            $this->addError('seo_title', 'The SEO title must contain the focus keyword.');
        }

        if ($this->description) {

            preg_match_all('/<h([3-6])[^>]*>/i', $this->description, $matches);

            if (!empty($matches[1])) {
                $lastLevel = 0;
                foreach ($matches[1] as $level) {
                    $level = intval($level);
                    if ($level < $lastLevel) {
                        $this->addError('description', 'Heading sequence is invalid. Headings must follow h2 → h3 → h4 → h5 → h6 order.');
                        break;
                    }
                    $lastLevel = $level;
                }
            }

            $words = explode(' ', strip_tags($this->description));
            $first100 = implode(' ', array_slice($words, 0, 100));

            if (stripos($first100, $focusLower) === false) {
                $this->addError('description', 'The description field first 100 words must contain the focus keyword.');
            }

            $result = CommonHelper::description_only_https($this->description);

            if (!$result) {
                $this->addError('description', 'The description field must only contain HTTPS URLs.');
                return;
            }

            preg_match_all('/<img[^>]*>/i', $this->description, $images);

            if (!empty($images[0])) {
                foreach ($images[0] as $index => $imgTag) {
                    preg_match('/alt=[\'"]([^\'"]*)[\'"]/i', $imgTag, $altMatch);

                    if (empty($altMatch[1]) || trim($altMatch[1]) === '') {
                        $this->addError('description', 'Image #' . ($index + 1) . ' must contain an alt attribute.');
                    } else {
                        $alt = trim($altMatch[1]);
                        if (mb_strlen($alt) > 100) {
                            $this->addError('description', 'Image #' . ($index + 1) . ' alt text must not exceed 100 characters.');
                        }
                    }
                }
            }
        }
    }

    // =========================================================================
    // VALIDATION RULES
    // =========================================================================

    protected function rules()
    {
        $id = $this->idToEdit ?? 'NULL';

        if ($this->is_gabbar != 2) {
            return [
                'focus_keyword' => "required",
                'title' => "required|between:45,70|unique:crypto_news,title,$id,id,deleted_at,NULL",
                'alias' => "required|max:65|unique:crypto_news,alias,$id,id,deleted_at,NULL|regex:/^[a-z0-9_-]+$/",
                'publishedAt' => 'required',
                'is_gabbar' => 'required',
                'status' => 'required',
                'image' => $this->updateMode ? 'nullable|mimes:jpeg,jpg,png,gif,webp,svg|max:200' : 'required|mimes:jpeg,jpg,png,gif,webp,svg|max:200',
                'description' => 'required',
                'img_alt_title' => ['required', 'max:100'],
                'seo_title' => "required|between:40,60|unique:crypto_news,seo_title,$id,id,deleted_at,NULL",
                // 'meta_keywords' => 'required|between:10,300|max_keyword_density',
                'meta_description' => "required|between:70,155|unique:crypto_news,meta_description,$id,id,deleted_at,NULL",
                'author_id' => 'required_without:author',
                'author' => 'required_without:author_id',
            ];
        } else {
            return [
                'focus_keyword' => "required",
                'title' => "required|unique:crypto_news,title,$id,id,deleted_at,NULL",
                'alias' => "required|unique:crypto_news,alias,$id,id,deleted_at,NULL|regex:/^[a-z0-9_-]+$/",
                'img_alt_title' => ['required', 'max:100'],
                'publishedAt' => 'required',
                'is_gabbar' => 'required',
                'status' => 'required',
                'image' => $this->updateMode ? 'nullable|mimes:jpeg,jpg,png,gif,webp,svg|max:200' : 'required|mimes:jpeg,jpg,png,gif,webp,svg|max:200',
                'description' => 'required',
                'seo_title' => "required|between:40,60|unique:crypto_news,seo_title,$id,id,deleted_at,NULL",
                'meta_keywords' => 'required|between:10,300|max_keyword_density',
                'meta_description' => "required|between:70,155|unique:crypto_news,meta_description,$id,id,deleted_at,NULL",
                'author_id' => 'required_without:author',
                'author' => 'required_without:author_id',
            ];
        }
    }

    protected function messages()
    {
        return [
            'focus_keyword.required' => 'Focus keyword is required.',
            'title.required' => 'Title is required.',
            'title.max' => 'Title must not be more than 70 characters.',
            'alias.required' => 'Alias is required.',
            'alias.unique' => 'This alias already exists. Please choose a different one.',
            'alias.max' => 'Alias must not be more than 65 characters.',
            'alias.regex' => 'Alias may only contain lowercase letters, numbers, hyphens, and underscores.',
            'publishedAt.required' => 'Published date is required.',
            'is_gabbar.required' => 'Please select whether this is Gabbar content or not.',
            'status.required' => 'Status is required.',
            'image.required' => 'Image is required.',
            'image.mimes' => 'Image must be one of the following formats: jpeg, jpg, png, gif, webp, svg.',
            'image.max' => 'Image size must not exceed 200 KB.',
            'description.required' => 'Description is required.',
            'seo_title.required' => 'SEO title is required.',
            'seo_title.min' => 'SEO title must be at least 45 characters.',
            'seo_title.max' => 'SEO title must not exceed 60 characters.',
            'img_alt_title.required' => 'Image alt title is required.',
            'img_alt_title.max' => 'Image alt title must not exceed 100 characters.',
            'meta_description.required' => 'Meta description is required.',
            'meta_description.min' => 'Meta description must be at least 130 characters.',
            'meta_description.max' => 'Meta description must not exceed 155 characters.',
            'author_id.required_without' => 'Please select an author or enter a new one.',
            'author.required_without' => 'Please enter an author name or select an author.',
        ];
    }

    // =========================================================================
    // RESET FIELDS
    // =========================================================================

    public function resetFields()
    {
        $this->reset([
            'idToEdit',
            'status',
            'author_id',
            'author_name',
            'user_id',
            'is_gabbar',
            'is_featured',
            'channel_id',
            'is_home',
            'is_review',
            'title',
            'alias',
            'interlink_url',
            'h1_title',
            'h2_title',
            'short_desc',
            'description',
            'url',
            'image',
            'img_alt_title',
            'is_thumb',
            'urlToImage',
            'word_file',
            'tags',
            'is_active',
            'is_rss_feed',
            'is_paid',
            'is_organic',
            'is_cryptotax',
            'is_seo_check',
            'publishedAt',
            'focus_keyword',
            'seo_title',
            'meta_keywords',
            'meta_description',
            'likes_counts',
            'article',
            'breadcrumbs',
            'course_info',
            'data_set',
            'discussion_forum',
            'events',
            'faq',
            'image_metadata',
            'project_name',
            'project_website',
            'project_id',
            'new_article',
            'paywalled_content',
            'product',
            'profile',
            'organization',
            'review_snippets',
            'sitelinks',
            'video',
            'dynamic_rss_feed',
            'dataset_level',
            'dataset_json',
            'update_status',
            'prompt_instructions',
            'is_guest'
        ]);

        $this->resetValidation();
        $this->updateMode = false;
        $this->formMode = false;

        // Clear draft state
        $this->draftId = null;
        $this->draftSavedAt = null;
    }

    // =========================================================================
    // SAVE (CREATE)
    // =========================================================================

    public function save()
    {
        if (!in_array(23, $this->permissions) && $this->role_id != 1) {
            session()->flash('error', 'You do not have permission to add a News.');
            return;
        }

        $this->validate();
        // $this->validateExtraSeoRules();
        if ($this->getErrorBag()->isNotEmpty()) {
            return; // Stop if SEO errors exist
        }

        if ($this->is_gabbar != 2) {

            $this->validate([
                'title' => 'required|string|max:255',
                'description' => 'required',
                'focus_keyword' => 'required|string',
            ]);
        }
        $folder = 'crypto-news/' . date('Y') . '/' . strtolower(date('F'));

        $path = $this->image ? $this->image->store($folder, 's3') : $this->oldImage ?? null;

        $userId = Auth::check() ? Auth::id() : 1;

        $data = [
            'author_id' => '1',
            'author_name' => $this->author_name,
            'user_id' => $userId,
            'is_gabbar' => $this->is_gabbar,
            'is_featured' => $this->is_featured ?? 0,
            'channel_id' => $this->channel_id ?? 1,
            'is_home' => $this->is_home ?? 0,
            'title' => $this->title,
            'alias' => $this->alias,
            'h1_title' => $this->h1_title,
            'h2_title' => $this->h2_title,
            'short_desc' => $this->short_desc,
            'description' => $this->description,
            'url' => $this->url,
            'image' => $path,
            'img_alt_title' => $this->img_alt_title,
            'urlToImage' => $this->urlToImage,
            'word_file' => $this->word_file,
            'tags' => $this->tags,
            'status' => $this->status,
            'is_rss_feed' => $this->is_rss_feed ?? 0,
            'is_paid' => $this->is_paid ?? 0,
            'is_organic' => $this->is_organic ?? 0,
            'is_cryptotax' => $this->is_cryptotax ?? 0,
            'publishedAt' => $this->publishedAt ? strtotime($this->publishedAt) : time(),
            'focus_keyword' => $this->focus_keyword,
            'seo_title' => $this->seo_title,
            'meta_keywords' => $this->meta_keywords,
            'meta_description' => $this->meta_description,
            'faq' => $this->faq,
            'project_name' => $this->project_name,
            'project_website' => $this->project_website,
            'project_id' => $this->project_id,
            'prompt_instructions' => $this->prompt_instructions
        ];

        $validator = Validator::make(
            $data,
            (new StoreCryptoNewsRequest)->rules($data),
            (new StoreCryptoNewsRequest)->messages()
        );

        $crypto = CryptoNewsModel::create($data);

        // Generate thumbnail + small thumbnail
        Artisan::call('crypto-news:thumbnails', [
            '--id' => $crypto->id,
        ]);

        // ── Delete draft on successful save ───────────────────────────────
        $this->discardDraft();
        // ─────────────────────────────────────────────────────────────────

        session()->flash('message', 'Crypto News added successfully.');
        $this->resetFields();
    }

    public function edit($id)
    {
        if (!in_array(25, $this->permissions) && $this->role_id != 1) {
            session()->flash('error', 'You do not have permission to edit News.');
            return;
        }

        $crypto = CryptoNewsModel::findOrFail($id);

        $this->idToEdit = $crypto->id;
        $this->author_id = $crypto->author_id;
        $this->author_name = $crypto->author_name;
        $this->user_id = $crypto->user_id;
        $this->is_gabbar = $crypto->is_gabbar;
        $this->is_featured = $crypto->is_featured;
        $this->channel_id = $crypto->channel_id;
        $this->is_home = $crypto->is_home;
        $this->title = $crypto->title;
        $this->alias = $crypto->alias;
        $this->h1_title = $crypto->h1_title;
        $this->h2_title = $crypto->h2_title;
        $this->short_desc = $crypto->short_desc;
        $this->description = $crypto->description;
        $this->url = $crypto->url;
        $this->oldImage = $crypto->getRawOriginal('image'); // Get raw image path without CDN URL
        $this->img_alt_title = $crypto->img_alt_title;
        $this->urlToImage = $crypto->urlToImage;
        $this->word_file = $crypto->word_file;
        $this->tags = $crypto->tags;
        $this->is_active = $crypto->is_active;
        $this->is_rss_feed = $crypto->is_rss_feed;
        $this->is_paid = $crypto->is_paid;
        $this->is_organic = $crypto->is_organic;
        $this->is_cryptotax = $crypto->is_cryptotax;
        $this->is_seo_check = $crypto->is_seo_check;
        $this->publishedAt = $crypto->publishedAt ? date('Y-m-d\TH:i', $crypto->publishedAt) : null;
        $this->focus_keyword = $crypto->focus_keyword;
        $this->seo_title = $crypto->seo_title;
        $this->meta_keywords = $crypto->meta_keywords;
        $this->meta_description = $crypto->meta_description;
        $this->article = $crypto->article;
        $this->breadcrumbs = $crypto->breadcrumbs;
        $this->course_info = $crypto->course_info;
        $this->data_set = $crypto->data_set;
        $this->discussion_forum = $crypto->discussion_forum;
        $this->events = $crypto->events;
        $this->faq = $crypto->faq;
        $this->image_metadata = $crypto->image_metadata;
        $this->project_name = $crypto->project_name;
        $this->project_website = $crypto->project_website;
        $this->project_id = $crypto->project_id;
        $this->new_article = $crypto->new_article;
        $this->paywalled_content = $crypto->paywalled_content;
        $this->product = $crypto->product;
        $this->profile = $crypto->profile;
        $this->organization = $crypto->organization;
        $this->review_snippets = $crypto->review_snippets;
        $this->sitelinks = $crypto->sitelinks;
        $this->video = $crypto->video;
        $this->dynamic_rss_feed = $crypto->dynamic_rss_feed;
        $this->dataset_level = $crypto->dataset_level;
        $this->dataset_json = $crypto->dataset_json;
        $this->status = $crypto->status;
        $this->prompt_instructions = $crypto->prompt_instructions;
        $this->updateMode = true;
        $this->formMode = true;

        $this->dispatch('load-editor', content: $this->description);
    }

    // =========================================================================
    // UPDATE
    // =========================================================================

    public function update()
    {
        $id = $this->idToEdit;
        if ($this->is_gabbar != 2) {
        $focusKeyword = $this->focus_keyword;
        $this->validate();

        if (!$focusKeyword) {
            return;
        }

        $validator = Validator::make($this->all(), []);

        $validator->after(function ($validator) use ($focusKeyword) {
            if (!$focusKeyword)
                return;

            $service = new FocusKeywordFieldsValidator($focusKeyword);

            $fieldsToCheck = [
                'title' => $this->title,
                'img_alt_title' => $this->img_alt_title,
                'meta_description' => $this->meta_description,
                'seo_title' => $this->seo_title,
                'h1_title' => $this->h1_title,
                'h2_title' => $this->h2_title,
            ];

            $errors = $service->validate($fieldsToCheck);

            foreach ($errors as $field => $messages) {
                foreach ($messages as $message) {
                    $validator->errors()->add($field, $message);
                }
            }
        });

        $validator->validate();

        if ($this->getErrorBag()->isNotEmpty()) {
            return;
        }

        $descriptionRules = [
            'required',
            new WordsBetween(300, 10000),
            new WebsiteInterlink(checkAnchorWordCount: true),
            new KeywordDensity(($this->is_seo_check == 1 || $this->is_review == 1)),
            new ExternalLink(),
            new DescriptionContentRule(),
        ];

        if ($focusKeyword) {
            $descriptionRules[] = new FocusKeywordDensity($focusKeyword);
        }


        $this->validate([
            'title' => [
                'required',
                'different:h2_title,description',
                'unique:common_seo,h1_title,' . $id . ',module_id,deleted_at,NULL',
                'between:45,60',
                new TitlePixelWidth(560, 16),
            ],
            'alias' => 'required|unique:common_slug,slug,' . $id . ',module_id,deleted_at,NULL|max:65|regex:/^\S*$/u',
            'img_alt_title' => 'required|unique:common_seo,img_alt_title,NULL,' . $id . ',deleted_at,NULL|between:15,80',
            'h1_title' => 'nullable|different:title|unique:common_seo,h1_title,NULL,id,deleted_at,NULL|between:30,70',
            'h2_title' => 'required|different:title,description|unique:common_seo,h2_title,' . $id . ',module_id,deleted_at,NULL|between:30,70',
            'meta_description' => [
                'required',
                'unique:common_seo,h1_title,' . $id . ',module_id,deleted_at,NULL',
                'between:130,155',
                new TitlePixelWidth(985, 12),
            ],
            'seo_title' => 'required|different:title,description|unique:common_seo,h1_title,' . $id . ',module_id,deleted_at,NULL|between:45,60',
            'publishedAt' => 'required',
            'is_gabbar' => 'required',
            'is_rss_feed' => 'required',
            'channel_id' => 'required',
            'faq' => [
                'required',
                function ($attribute, $value, $fail) {

                    // Step 1: Decode if string
                    if (is_string($value)) {
                        $decoded = json_decode($value, true);

                        if (json_last_error() !== JSON_ERROR_NONE) {
                            return $fail('Invalid format for FAQ.');
                        }

                        $value = $decoded;
                    }

                    // Step 2: Must be array
                    if (!is_array($value)) {
                        return $fail('Invalid format for FAQ.');
                    }

                    // Step 3: Validate structure FIRST
                    foreach ($value as $faq) {

                        if (
                            !is_array($faq) ||
                            count($faq) !== 2 ||
                            !array_key_exists('question', $faq) ||
                            !array_key_exists('answer', $faq) ||
                            !is_string($faq['question']) ||
                            !is_string($faq['answer']) ||
                            trim($faq['question']) === '' ||
                            trim($faq['answer']) === ''
                        ) {
                            return $fail('Invalid format for FAQ.');
                        }
                    }

                    // Step 4: NOW check count (separate error)
                    if (count($value) < 5) {
                        return $fail('Minimum 5 FAQs required.');
                    }
                },
            ],
            // 'faqs' => 'nullable|array|min:5',
            // 'faqs.*.question' => 'required_with:faqs.*.answer|string|nullable',
            // 'faqs.*.answer' => 'required_with:faqs.*.question|string|nullable',
            'is_home' => 'required|numeric',
            // 'meta_keywords' => ['required', new NoDuplicateKeywordsRule()],
            'description' => $descriptionRules,
            'focus_keyword' => 'required|string',
        ]);
        }else
        {

         $this->validate([
            'title' => 'required',
            'alias' => 'required',
            'img_alt_title' => 'required',
            'h1_title' => 'nullable',
            'h2_title' => 'required',
            'meta_description' =>'required',
            'seo_title' => 'required',
            'publishedAt' => 'required',
            'is_gabbar' => 'required',
            'is_rss_feed' => 'required',
            'channel_id' => 'required',
            'faqs' => 'nullable|array|min:5',
            'faqs.*.question' => 'required_with:faqs.*.answer|string|nullable',
            'faqs.*.answer' => 'required_with:faqs.*.question|string|nullable',
            'is_home' => 'required|numeric',
            // 'meta_keywords' => 'required',
            'description' => 'required',
            'focus_keyword' => 'required|string',
        ]);
        }

        $userId = Auth::check() ? Auth::id() : 1;
        $crypto = CryptoNewsModel::findOrFail($this->idToEdit);

        $folder = 'crypto-news/' . date('Y') . '/' . strtolower(date('F'));
        $imagePath = $crypto->getRawOriginal('image');

        // Image change detect
        $imageChanged = false;

        if ($this->image) {
            $imagePath = $this->image->store($folder, 's3');
            $imageChanged = true;
        }

        $crypto->update([
            'author_id' => $this->author_id,
            'author_name' => $this->author_name,
            'author' => $this->author,
            'is_gabbar' => $this->is_gabbar,
            'is_featured' => $this->is_featured ?? 0,
            'channel_id' => $this->channel_id ?? 2,
            'created_by' => $this->created_by,
            'is_home' => $this->is_home ?? 0,
            'title' => $this->title,
            'alias' => $this->alias,
            'h1_title' => $this->h1_title,
            'h2_title' => $this->h2_title,
            'short_desc' => $this->short_desc,
            'description' => $this->description,
            'url' => $this->url,
            'image' => $imagePath,
            'img_alt_title' => $this->img_alt_title,
            'urlToImage' => $this->urlToImage,
            'is_rss_feed' => $this->is_rss_feed ?? 0,
            'is_paid' => $this->is_paid ?? 0,
            'is_organic' => $this->is_organic ?? 0,
            'is_seo_check' => $this->is_seo_check ?? 0,
            'status' => $this->status,
            'publishedAt' => $this->publishedAt ? strtotime($this->publishedAt) : null,
            'focus_keyword' => $this->focus_keyword,
            'seo_title' => $this->seo_title,
            'meta_keywords' => $this->meta_keywords,
            'meta_description' => $this->meta_description,
            'article' => $this->article,
            'breadcrumbs' => $this->breadcrumbs,
            'data_set' => $this->data_set,
            'discussion_forum' => $this->discussion_forum,
            'faq' => $this->faq,
            'image_metadata' => $this->image_metadata,
            'new_article' => $this->new_article,
            'paywalled_content' => $this->paywalled_content,
            'profile' => $this->profile,
            'organization' => $this->organization,
            'review_snippets' => $this->review_snippets,
            'is_review' => $this->is_review ?? 0,
            'sitelinks' => $this->sitelinks,
            'video' => $this->video,
            'dynamic_rss_feed' => $this->dynamic_rss_feed,
            'project_name' => $this->project_name,
            'project_website' => $this->project_website,
            'prompt_instructions' => $this->prompt_instructions,

            // New image => old thumbnail status reset
            ...($imageChanged ? [
                'is_thumb' => 0,
                'is_small' => 0,
            ] : []),
        ]);

        // New image => generate thumbnail + small thumbnail
        if ($imageChanged) {
            \Illuminate\Support\Facades\Artisan::call('crypto-news:thumbnails', [
                '--id' => $crypto->id,
            ]);
        }

        $this->updateSluginCommonModule($crypto);
        $this->updateseoinCommonModuleexits($crypto);

        session()->flash('message', 'Crypto updated successfully.');
        $this->resetFields();
    }

    // =========================================================================
    // VIEW / DELETE / SEARCH
    // =========================================================================

    public function view($id)
    {
        if (!in_array(24, $this->permissions) && $this->role_id != 1) {
            session()->flash('error', 'You do not have permission to view News.');
            return;
        }
        $this->cryptoToView = CryptoNewsModel::with('postAuthor','users')->findOrFail($id);
        $this->viewMode = true;
        $this->updateMode = false;
        $this->formMode = false;
    }

    public function delete($id)
    {
        if (!in_array(26, $this->permissions) && $this->role_id != 1) {
            session()->flash('error', 'You do not have permission to delete News.');
            return;
        }
        CryptoNewsModel::findOrFail($id)->delete();
        session()->flash('message', 'Crypto deleted successfully.');
    }

    public function applySearch()
    {
        $this->resetPage();
    }

    public function resetFilters()
    {
        $this->reset(['search', 'month','is_guest', 'author_id', 'is_seo_check', 'alias', 'title', 'is_gabbar', 'startDatePublish', 'endDatePublish', 'startDateCreated', 'endDateCreated']);
        $this->resetPage();
    }

    // =========================================================================
    // RENDER
    // =========================================================================
    public function resumeDraftFromList(int $draftId): void
    {
        $this->formMode = true;
        $this->updateMode = false;
        $this->resumeDraft($draftId);
    }
    public function render()
    {
        $query = CryptoNewsModel::with('postAuthor');
        $channels = Channel::where('is_active', 1)->get();

        $authors = AuthorModel::where('is_active', 1)
            ->where(function ($q) {
                $q->where('user_type', 0)
                    ->orWhere('user_type', 4);
            })
            ->orderBy('order_by')
            ->get();

        // Search filter
        if (!empty($this->search)) {
            $search = trim($this->search);
            $query->where(function ($q) use ($search) {
                $q->where('alias', 'like', "%{$search}%")
                    ->orWhere('title', 'like', "%{$search}%")
                    ->orWhere('seo_title', 'like', "%{$search}%");
            });
        }
        if (!empty($this->startDatePublish) && !empty($this->endDatePublish)) {
            $start = Carbon::parse($this->startDatePublish)->startOfDay()->timestamp;
            $end   = Carbon::parse($this->endDatePublish)->endOfDay()->timestamp;

            $query->whereBetween('publishedAt', [$start, $end]);
        }

        if (!empty($this->startDateCreated) && !empty($this->endDateCreated)) {
            $query->whereBetween('created_at', [
                Carbon::parse($this->startDateCreated)->startOfDay(),
                Carbon::parse($this->endDateCreated)->endOfDay()
            ]);
        }

        // Month filter
        if (!empty($this->month)) {
            $query->whereMonth('created_at', $this->month);
        }

        // Created By filter
        if (!empty($this->author_id)) {
            $query->where('author_id', $this->author_id);
        }

        // Review filter
        if ($this->is_seo_check !== '' && $this->is_seo_check !== null) {
            $query->where('is_seo_check', $this->is_seo_check);
        }

        // Gabbar filter
        if ($this->is_gabbar !== '' && $this->is_gabbar !== null) {
            $query->where('is_gabbar', $this->is_gabbar);
        }

        // Gabbar filter
        if ($this->is_guest !== '' && $this->is_guest !== null) {
            $query->where('is_guest', $this->is_guest);
        }

        return view('livewire.admin.crypto-news', [
            'cryptos' => $query->latest()->paginate($this->perPage),
            'authors' => $authors,
            'channels' => $channels,
        ])->layout('admin.layouts.base');
    }

    // =========================================================================
    // COMMON MODULE HELPERS
    // =========================================================================

    public function updateSluginCommonModule($cryptoNews)
    {
        $module_flag = $this->resolveModuleFlag($cryptoNews->is_gabbar);

        commonSlug::create([
            'slug' => $cryptoNews->alias,
            'module_flag' => $module_flag,
            'module_id' => $cryptoNews->id,
        ]);
    }

    public function updateSluginCommonModuleexits($cryptoNews)
    {
        $commonSlug = commonSlug::where('module_id', $cryptoNews->id)->first();
        $module_flag = $this->resolveModuleFlag($cryptoNews->is_gabbar);

        $data = [
            'slug' => $cryptoNews->alias,
            'module_flag' => $module_flag,
            'module_id' => $cryptoNews->id,
        ];

        $commonSlug ? $commonSlug->update($data) : commonSlug::create($data);
    }

    public function updateseoinCommonModuleexits($cryptoNews)
    {
        $commondata = commonSEO::where('module_id', $cryptoNews->id)->first();
        $module_flag = $this->resolveModuleFlag($cryptoNews->is_gabbar);

        $data = [
            'slug' => $cryptoNews->alias,
            'module_flag' => $module_flag,
            'module_id' => $cryptoNews->id,
            'h1_title' => $cryptoNews->title,
            'h2_title' => $cryptoNews->h2_title,
            'seo_title' => $cryptoNews->seo_title,
            'meta_keywords' => $cryptoNews->meta_keywords,
            'meta_description' => $cryptoNews->meta_description,
        ];

        $commondata ? $commondata->update($data) : commonSEO::create($data);
    }

    private function resolveModuleFlag($isGabbar): ?string
    {
        if ($isGabbar == 1)
            return 'gabbar-news';
        if ($isGabbar == 2)
            return 'press-release';
        return null;
    }

    public function exportNews()
    {
        $fileName = 'presale-news.csv';

        return response()->streamDownload(function () {

            $handle = fopen('php://output', 'w');

            $columns = Schema::getColumnListing('crypto_news');

            fputcsv($handle, $columns);

            CryptoNewsModel::query()
                ->where('is_active', 1)
                ->where('is_seo_check', 1)
                ->where('publishedAt', '<=', time())
                ->whereNull('deleted_at')
                ->orderByDesc('id')
                ->chunk(500, function ($news) use ($handle, $columns) {
                    foreach ($news as $row) {
                        $data = [];

                        foreach ($columns as $column) {
                            $value = $row->{$column};

                            if (is_array($value) || is_object($value)) {
                                $value = json_encode($value, JSON_UNESCAPED_UNICODE);
                            }

                            $data[] = $value;
                        }

                        fputcsv($handle, $data);
                    }
                });

            fclose($handle);

        }, $fileName, [
            'Content-Type' => 'text/csv; charset=UTF-8',
        ]);
    }
}
