<?php

namespace App\Livewire\Admin;

use App\Models\commonSEO;
use Livewire\Component;
use Livewire\WithPagination;
use App\Models\{CryptoNewsModel, AuthorModel, Channel, commonSlug};
use App\Models\CryptoNewsDraft;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use App\Services\PermissionService;
use App\Helpers\CommonHelper;
use App\Rules\WordsBetweenRule;
use App\Rules\WebsiteInterlinkRule;
use App\Rules\ExternalLinkRule;
use App\Rules\FocusKeywordDensityRule;
use App\Rules\KeywordDensityRule;
use App\Rules\NoDuplicateKeywordsRule;
use App\Rules\DescriptionContentRule;
use App\Rules\TitlePixelWidth;
use App\Services\FocusKeywordFieldsValidator;
use App\Traits\WithActiveDeactive;
use App\Traits\WithDelete;
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;
    // Form fields
    public $channel;
    public $idToEdit;
    public $author_id;
    public $author_name;
    public $author;
    public $user_id;
    public $is_gabbar;
    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 $categories;
    public $tags;
    public $is_active = 1;
    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 $startDatePublish;
    public $endDatePublish;
    public $startDateCreated;
    public $endDateCreated;
    // ── Draft ──────────────────────────────────────────────────────────────
    public $draftId = null;
    public $draftSavedAt = null;
    public $showDraftModal = false;
    public $permissions = [];
    public $role_id;
    public $prompt_instructions;
    protected $listeners = [
        'triggerDraftSave' => 'saveDraft',
    ];

    protected $paginationTheme = 'bootstrap';


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

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

        if (!in_array(14, $this->permissions) && $this->role_id != 1) {
            session()->flash('error', 'You do not have permission to access Crypto 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));
        });
    }

    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) {
            $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;
            }
        }
    }

    protected function prepareForValidation($attributes)
    {
        if (isset($attributes['faq']) && is_string($attributes['faq'])) {
            $decoded = json_decode($attributes['faq'], true);

            if (json_last_error() === JSON_ERROR_NONE) {
                $attributes['faq'] = $decoded;
            }
        }

        return $attributes;
    }

    protected function rules()
    {
        $id = $this->idToEdit ?? 'NULL';
        if ($this->is_gabbar != 2) {
            return [
                'focus_keyword' => "required",
                'title' => "required|min:50|max:60",
                'alias' => 'required|max:65|unique:common_slug,slug,' . $id . ',module_id,deleted_at,NULL|regex:/^[a-z0-9_-]+$/',
                'publishedAt' => 'required',
                'is_gabbar' => 'required',
                'status' => 'required',
                'h1_title' => "required|between:45,60",
                'img_alt_title' => [
                    'required',
                    'max:100'
                ],

                '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',
                    'regex:/<h2[^>]*>.*?<\/h2>/is'
                ],

                'seo_title' => [
                    'required',
                    'min:45',
                    'max:55'
                ],

                'meta_description' => [
                    'required',
                    'min:130,',
                    'max:160'
                ],

                'author_id' => 'required_without:author_name',
                'author_name' => 'required_without:author_id',
                '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.');
                        }
                    },
                ],
            ];
        } else {
            return [
                'focus_keyword' => "required|unique:crypto_news,focus_keyword,$id,id,deleted_at,NULL",
                '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:500'
                    : 'required|mimes:jpeg,jpg,png,gif,webp,svg|max:500',

                'description' => 'required',

                'seo_title' => "required|between:40,60|unique:crypto_news,seo_title,$id,id,deleted_at,NULL",

                // 'meta_keywords' => 'required|between:10,300',

                'meta_description' =>
                "required|between:130,155|unique:crypto_news,meta_description,$id,id,deleted_at,NULL",

                'author_id' => 'required_without:author_name',
                'author_name' => 'required_without:author_id',
                'faq' => [
                    'required',
                    'array',
                    'min:5',
                    function ($attribute, $value, $fail) {

                        // ✅ Check main structure
                        if (!is_array($value)) {
                            return $fail('Invalid format for FAQ.');
                        }

                        foreach ($value as $index => $faq) {

                            // ✅ Each item must be array with required keys
                            if (
                                !is_array($faq) ||
                                !array_key_exists('question', $faq) ||
                                !array_key_exists('answer', $faq)
                            ) {
                                return $fail('Invalid format for FAQ.');
                            }

                            // ✅ Now validate content
                            if (empty(trim($faq['question']))) {
                                $fail("FAQ question is required at position " . ((int)$index + 1));
                            }

                            if (empty(trim($faq['answer']))) {
                                $fail("FAQ answer is required at position " . ((int)$index + 1));
                            }
                        }
                    },
                ],
            ];
        }
    }

    protected function messages()
    {
        return [

            'focus_keyword.required' => 'Focus keyword is required.',

            'title.required' => 'Title is required.',
            'title.min' => 'Title must be more than 50 characters.',
            'title.max' => 'Title must not be more than 60 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.',

            'h1_title.required' => 'H1 title is required.',
            'h1_title.min' => 'H1 Title must not be more than 45 characters.',
            'h1_title.max' => 'H1 Title must not be more than 60 characters.',

            '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.',
            'description.regex' => 'Description must contain at least one <h2> heading.',

            '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 55 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_name.required_without' => 'Please enter an author name or select an author.',
        ];
    }


    public function resetFields()
    {
        $this->reset([
            'idToEdit',
            'status',
            'author_id',
            'author_name',
            'user_id',
            'is_gabbar',
            'is_featured',
            'channel_id',
            'is_home',
            'title',
            'alias',
            'interlink_url',
            'h1_title',
            'h2_title',
            'short_desc',
            'description',
            'url',
            'categories',
            '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'
        ]);
        $this->resetValidation();
        $this->updateMode = false;
        $this->formMode = false;
        // Clear draft state
        $this->draftId = null;
        $this->draftSavedAt = null;
        $this->showDraftModal = false;
    }

    public function save()
    {
        if (!in_array(15, $this->permissions) && $this->role_id != 1) {
            session()->flash('error', 'You do not have permission to Add Crypto News.');
            return redirect()->route('admin.dashboard');
        }
        $this->validate();
        // $this->validateExtraSeoRules();

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

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

            $this->validate([
                'title' => 'required|string|max:255',
                'description' => 'required',
                'focus_keyword' => 'required|string',
            ]);
        } else {
            $this->validate([
                'description' => 'required',
                'title' => 'required',
                'focus_keyword' => 'required|string',
            ]);
        }

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

        if ($this->image) {
            $path = $this->image->store($folder, 's3');
        } else {
            $path = $this->oldImage ?? null;
        }
        $userId = Auth::check() ? Auth::id() : 1;
        $data = [
            'author_id' => $this->author_id,
            '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,
            'is_thumb' => 0,
            'is_small' => 0,
            'urlToImage' => $this->urlToImage,
            'word_file' => $this->word_file,
            'tags' => $this->tags,
            'status' => $this->status,
            'is_active' => $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,
            'is_seo_check' => 0,
            'publishedAt' => $this->publishedAt ? Carbon::parse($this->publishedAt, 'Asia/Kolkata')->timestamp : null,
            'focus_keyword' => $this->focus_keyword,
            'seo_title' => $this->seo_title,
            'meta_keywords' => $this->meta_keywords,
            'meta_description' => $this->meta_description,
            'likes_counts' => 0,
            'article' => $this->article,
            'breadcrumbs' => $this->breadcrumbs,
            'course_info' => $this->course_info,
            'data_set' => $this->data_set,
            'discussion_forum' => $this->discussion_forum,
            'events' => $this->events,
            'faq' => $this->faq,
            'image_metadata' => $this->image_metadata,
            'project_name' => $this->project_name,
            'project_website' => $this->project_website,
            'project_id' => $this->project_id,
            'new_article' => $this->new_article,
            'paywalled_content' => $this->paywalled_content,
            'product' => $this->product,
            'profile' => $this->profile,
            'organization' => $this->organization,
            'review_snippets' => $this->review_snippets,
            'sitelinks' => $this->sitelinks,
            'video' => $this->video,
            'dynamic_rss_feed' => $this->dynamic_rss_feed,
            'dataset_level' => $this->dataset_level,
            'dataset_json' => $this->dataset_json,
            'update_status' => 0,
            'prompt_instructions' => $this->prompt_instructions
        ];
        $cryptoNews = CryptoNewsModel::create($data);

        // Generate thumbnails for newly uploaded image
        if ($this->image) {
            Artisan::call('crypto-news:thumbnails', [
                '--id' => $cryptoNews->id,
            ]);

            // Thumbnail generation successful
            $cryptoNews->update([
                'is_thumb' => 1,
                'is_small' => 1,
            ]);
        }

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

        $this->discardDraft();

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

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

        $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->categories = explode(',', $crypto->categories);
        $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
            ? Carbon::createFromTimestamp($crypto->publishedAt)
            ->setTimezone('Asia/Kolkata')
            ->format('Y-m-d\TH:i')
            : 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->prompt_instructions = $crypto->prompt_instructions;

        $this->status = $crypto->status;
        $this->updateMode = true;
        $this->formMode = true;
        $this->dispatch('load-editor', content: $this->description);
    }

    public function update()
    {
        $this->validate();

        // ── 1. Build description rules ─────────────────────────────────────
        $descriptionRules = [
            'required',
            new WordsBetweenRule(300, 10000),
            new WebsiteInterlinkRule(checkAnchorWordCount: true),
            new KeywordDensityRule(true),
            new ExternalLinkRule(),
            new DescriptionContentRule(),
        ];

        if ($this->focus_keyword) {
            $descriptionRules[] = new FocusKeywordDensityRule($this->focus_keyword);
        }

        // ── 2. Run main validation first ───────────────────────────────────
        $this->validate([
            'title' => new TitlePixelWidth(560, 16),
            'description' => $descriptionRules,
            // 'meta_keywords' => ['required', new NoDuplicateKeywordsRule()],
            'meta_description' => new TitlePixelWidth(985, 12),
        ]);

        // ── 3. Run focus keyword validation after main passes ───────────────
        if ($this->focus_keyword) {
            $service = new FocusKeywordFieldsValidator($this->focus_keyword);

            $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);

            if ($this->description) {
                $descErrors = $service->validateDescription($this->description);
                $errors = array_merge_recursive($errors, $descErrors);
            }

            if (!empty($errors)) {
                $messages = [];

                foreach ($errors as $field => $fieldMessages) {
                    foreach ($fieldMessages as $message) {
                        $messages[$field][] = $message;
                    }
                }

                throw \Illuminate\Validation\ValidationException::withMessages($messages);
            }
        }

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

        // ── Get existing record ─────────────────────────────────────────────
        $crypto = CryptoNewsModel::findOrFail($this->idToEdit);

        $oldIsThumb = $crypto->is_thumb;
        $oldIsSmall = $crypto->is_small;

        $imageChanged = false;

        $imagePath = $crypto->getRawOriginal('image');

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

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

        $oldIsThumb = $crypto->is_thumb;
        $oldIsSmall = $crypto->is_small;

        $imagePath = $crypto->getRawOriginal('image');

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

        $imageChanged = false;

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

        // Generate thumbnails when:
        // 1. New image uploaded
        // OR
        // 2. Existing image is missing thumb
        // OR
        // 3. Existing image is missing small
        $needsThumbnailGeneration =
            $imageChanged ||
            (int) $oldIsThumb !== 1 ||
            (int) $oldIsSmall !== 1;

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

        $crypto->update([
            //'user_id' => $userId,
            'author_id' => $this->author_id,
            'author_name' => $this->author_name,
            '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' => $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,
            'is_active' => $this->status,
            'tags' => $this->tags,
            'publishedAt' => $this->publishedAt
                ? Carbon::parse($this->publishedAt, 'Asia/Kolkata')->timestamp
                : 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,
            '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,

            // Reset thumbnail flags ONLY when new image is uploaded
            ...($imageChanged ? [
                'is_thumb' => 0,
                'is_small' => 0,
            ] : []),
        ]);

       if ($needsThumbnailGeneration) {
            Artisan::call('crypto-news:thumbnails', [
                '--id' => $crypto->id,
            ]);

            // Mark both thumbnails as generated
            $crypto->update([
                'is_thumb' => 1,
                'is_small' => 1,
            ]);
        }

        // ── Generate thumbnails ONLY when image changed ─────────────────────
        // if ($imageChanged) {
        //     \Illuminate\Support\Facades\Artisan::call(
        //         'crypto-news:thumbnails',
        //         [
        //             '--id' => $crypto->id,
        //         ]
        //     );
        // }

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

        session()->flash('message', 'Crypto updated successfully.');

        $this->resetFields();
    }

    public function view($id)
    {
        if (!in_array(16, $this->permissions) && $this->role_id != 1) {
            session()->flash('error', 'You do not have permission to View Crypto News.');
            return redirect()->route('admin.dashboard');
        }

        $this->cryptoToView = CryptoNewsModel::with('postAuthor')->findOrFail($id);
        $this->viewMode = true;
        $this->updateMode = false;
        $this->formMode = false;
    }

    public function delete($id)
    {
        if (!in_array(18, $this->permissions) && $this->role_id != 1) {
            session()->flash('error', 'You do not have permission to Delete Crypto News.');
            return redirect()->route('admin.dashboard');
        }

        CryptoNewsModel::findOrFail($id)->delete();
        session()->flash('message', 'Crypto deleted successfully.');
    }

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

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

    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}%");
            });
        }

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

        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()
            ]);
        }

        // 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);
        }

        return view('livewire.admin.crypto-news', ['cryptos' => $query->latest()->paginate($this->perPage),'authors' => $authors,'channels' => $channels,])->layout('admin.layouts.base');
    }
    public function updateSluginCommonModule($cryptoNews)
	{
		if ($cryptoNews->is_gabbar == 1) {
			$module_flag = 'gabbar-news';
		} elseif ($cryptoNews->is_gabbar == 2) {
			$module_flag = 'press-release';
		} else {
			$module_flag = 'sponsored';
		}

		$cryptoNewsArr = array('slug' => $cryptoNews->alias, 'module_flag' => $module_flag, 'module_id' => $cryptoNews->id);
		$commonSlug = commonSlug::create($cryptoNewsArr);
	}
    public function updateSluginCommonModuleexits($cryptoNews)
	{
		$commonSlug = commonSlug::where('module_id', '=', $cryptoNews->id)->first();

		if ($cryptoNews->is_gabbar == 1) {
			$module_flag = 'gabbar-news';
		} elseif ($cryptoNews->is_gabbar == 2) {
			$module_flag = 'press-release';
		} else {
			$module_flag = 'sponsored';
		}
		$cryptoNewsArr = array('slug' => $cryptoNews->alias, 'module_flag' => $module_flag, 'module_id' => $cryptoNews->id);
		if (!empty($commonSlug)) {
			$commonSlug->update($cryptoNewsArr);
		} else {
			$commonSlug = commonSlug::create($cryptoNewsArr);
		}
	}
    public function updateseoinCommonModuleexits($cryptoNews)
	{
		$commondata = commonSEO::where('module_id', '=', $cryptoNews->id)->first();

		if ($cryptoNews->is_gabbar == 1) {
			$module_flag = 'gabbar-news';
		} elseif ($cryptoNews->is_gabbar == 2) {
			$module_flag = 'press-release';
		} elseif ($cryptoNews->is_gabbar == 5) {
			$module_flag = 'price-prediction';
		} elseif ($cryptoNews->is_gabbar == 6) {
			$module_flag = 'blog';
		} else {
			$module_flag = 'sponsored';
		}
		$cryptoNewsArr = array(
			'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
		);

		if (!empty($commondata)) {
			$commondata->update($cryptoNewsArr);
		} else {
			$commondata = commonSEO::create($cryptoNewsArr);
		}
	}

    // =========================================================================
    // 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(),
            );
        }
    }
    public function showDrafts(): void
    {   
        $this->showDraftModal = true;
        $this->formMode = false;
        $this->dispatch('toggle-drafts');
    }
    public function closeDraftModal(): void
    {
        $this->showDraftModal = false;
        $this->formMode = false;
    }
    // =========================================================================
    // 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 || !$this->alias) {
            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,
            '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(
            ['id' => $this->draftId , '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',
            '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 resumeDraftFromList(int $draftId): void
    {
        $this->formMode = true;
        $this->updateMode = false;
        $this->resumeDraft($draftId);
    }
}
