<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\ApiBaseController;
use App\Http\Requests\Api\WebsitePage\IndexRequest;
use App\Http\Requests\Api\WebsitePage\StoreRequest;
use App\Http\Requests\Api\WebsitePage\UpdateRequest;
use App\Http\Requests\Api\WebsitePage\DeleteRequest;
use App\Models\Website;
use App\Models\WebsiteBuilder;
use App\Models\WebsiteLanguage;
use App\Models\WebsitePage;
use App\Models\WebsitePageTranslation;
use Examyou\RestAPI\ApiResponse;
use Vinkla\Hashids\Facades\Hashids;

class WebsitePageController extends ApiBaseController
{
    protected $model = WebsitePage::class;

    protected $indexRequest = IndexRequest::class;
    protected $storeRequest = StoreRequest::class;
    protected $updateRequest = UpdateRequest::class;
    protected $deleteRequest = DeleteRequest::class;

    /**
     * Modify index query
     * Filter by website_id and eager load translations
     */
    protected function modifyIndex($query)
    {
        $request = request();

        // Filter by website_id if provided
        if ($request->has('website_id') && $request->input('website_id') && $request->input('website_id') !== 'null') {
            $decodedWebsiteId = Hashids::decode($request->input('website_id'));
            if (!empty($decodedWebsiteId)) {
                $query->where('website_id', $decodedWebsiteId[0]);
            }
        }

        // Eager load all translations with websiteLanguage data
        $query->with(['translations.websiteLanguage']);

        return $query;
    }

    /**
     * Store a new website page
     */
    public function store()
    {
        // Validate the request first
        $this->validate();

        \DB::beginTransaction();

        $request = request();

        // Create the website page
        $websiteId = $this->getIdFromHash($request->website_id);

        // Calculate next sort_order for this website
        $maxSortOrder = WebsitePage::where('website_id', $websiteId)->max('sort_order') ?? 0;

        $websitePage = new WebsitePage();
        $websitePage->page_key = $request->page_key;
        $websitePage->website_id = $websiteId;
        $websitePage->sort_order = $maxSortOrder + 1;
        $websitePage->save();

        // Create translations for each language from request
        $translations = $request->translations ?? [];

        foreach ($translations as $translationData) {
            $langId = $this->getIdFromHash($translationData['website_language_id']);

            if ($langId) {
                $translation = new WebsitePageTranslation();
                $translation->website_page_id = $websitePage->id;
                $translation->website_language_id = $langId;
                $translation->name = $translationData['name'] ?? '';
                $translation->show_in_header = $translationData['show_in_header'] ?? false;
                $translation->save();
            }
        }

        // Sync header/footer sections from existing pages based on website settings
        $this->syncHeaderFooterForNewPage($websitePage, $websiteId);

        \DB::commit();

        $meta = ['time' => round(microtime(true) - LARAVEL_START, 3)];

        return ApiResponse::make("Resource created successfully", ["xid" => $websitePage->xid], $meta);
    }

    /**
     * Update a website page
     */
    public function update(...$args)
    {
        // Validate the request first
        $this->validate();

        \DB::beginTransaction();

        $request = request();

        $xid = last(func_get_args());
        $convertedId = Hashids::decode($xid);
        $id = $convertedId[0];

        // Get and update the website page
        $websitePage = WebsitePage::find($id);

        if (!$websitePage) {
            return ApiResponse::make("Resource not found", null, [], 404);
        }

        $websitePage->page_key = $request->page_key;

        // Update sort_order if provided
        if ($request->has('sort_order')) {
            $websitePage->sort_order = $request->sort_order;
        }

        $websitePage->save();

        // Update all translations
        $translations = $request->translations ?? [];

        foreach ($translations as $translationData) {
            $langId = $this->getIdFromHash($translationData['website_language_id']);

            if ($langId) {
                $translation = WebsitePageTranslation::where('website_page_id', $websitePage->id)
                    ->where('website_language_id', $langId)
                    ->first();

                if ($translation) {
                    $translation->name = $translationData['name'] ?? $translation->name;
                    $translation->show_in_header = $translationData['show_in_header'] ?? false;
                    $translation->save();
                } else {
                    // Create translation if it doesn't exist
                    $translation = new WebsitePageTranslation();
                    $translation->website_page_id = $websitePage->id;
                    $translation->website_language_id = $langId;
                    $translation->name = $translationData['name'] ?? '';
                    $translation->show_in_header = $translationData['show_in_header'] ?? false;
                    $translation->save();
                }
            }
        }

        \DB::commit();

        $meta = ['time' => round(microtime(true) - LARAVEL_START, 3)];

        return ApiResponse::make("Resource updated successfully", ["xid" => $websitePage->xid], $meta);
    }

    /**
     * Prevent deletion of home page
     */
    public function destroying(WebsitePage $websitePage)
    {
        if ($websitePage->page_key === 'home') {
            throw new \Examyou\RestAPI\Exceptions\ApiException('Home page cannot be deleted');
        }

        return $websitePage;
    }

    /**
     * Sync header/footer sections from existing pages to a newly created page
     * Based on website's use_same_header_across_all_pages and use_same_footer_across_all_pages settings
     *
     * @param WebsitePage $newPage
     * @param int $websiteId
     * @return void
     */
    private function syncHeaderFooterForNewPage(WebsitePage $newPage, int $websiteId): void
    {
        $companyId = company()->id;

        // Get the website to check settings
        $website = Website::find($websiteId);
        if (!$website) {
            return;
        }

        // Get all languages for this website
        $languages = WebsiteLanguage::where('company_id', $companyId)
            ->where('website_id', $websiteId)
            ->get();

        // Find an existing page with header/footer sections (preferably home page)
        $sourcePage = WebsitePage::where('website_id', $websiteId)
            ->where('id', '!=', $newPage->id)
            ->where('page_key', 'home')
            ->first();

        // If no home page, get any other page
        if (!$sourcePage) {
            $sourcePage = WebsitePage::where('website_id', $websiteId)
                ->where('id', '!=', $newPage->id)
                ->first();
        }

        if (!$sourcePage) {
            return;
        }

        // Sync header if enabled
        if ($website->use_same_header_across_all_pages) {
            $this->copySectionToNewPage('header', $sourcePage->id, $newPage->id, $websiteId, $companyId, $languages);
        }

        // Sync footer if enabled
        if ($website->use_same_footer_across_all_pages) {
            $this->copySectionToNewPage('footer', $sourcePage->id, $newPage->id, $websiteId, $companyId, $languages);
        }
    }

    /**
     * Copy a section from source page to new page for all languages
     *
     * @param string $sectionKey
     * @param int $sourcePageId
     * @param int $newPageId
     * @param int $websiteId
     * @param int $companyId
     * @param \Illuminate\Database\Eloquent\Collection $languages
     * @return void
     */
    private function copySectionToNewPage(string $sectionKey, int $sourcePageId, int $newPageId, int $websiteId, int $companyId, $languages): void
    {
        foreach ($languages as $lang) {
            // Get source section for this language
            $sourceSection = WebsiteBuilder::where('company_id', $companyId)
                ->where('website_id', $websiteId)
                ->where('website_page_id', $sourcePageId)
                ->where('website_language_id', $lang->id)
                ->where('section_key', $sectionKey)
                ->first();

            if ($sourceSection) {
                // Check if section already exists for new page
                $exists = WebsiteBuilder::where('company_id', $companyId)
                    ->where('website_id', $websiteId)
                    ->where('website_page_id', $newPageId)
                    ->where('website_language_id', $lang->id)
                    ->where('section_key', $sectionKey)
                    ->exists();

                if (!$exists) {
                    WebsiteBuilder::create([
                        'company_id' => $companyId,
                        'website_id' => $websiteId,
                        'website_page_id' => $newPageId,
                        'website_language_id' => $lang->id,
                        'section_key' => $sectionKey,
                        'section_layout' => $sourceSection->section_layout,
                        'title' => $sourceSection->title,
                        'subtitle' => $sourceSection->subtitle ?? '',
                        'content' => $sourceSection->content,
                        'content_schema' => $sourceSection->content_schema,
                        'sort_order' => $sourceSection->sort_order ?? 0,
                        'is_white_background' => $sourceSection->is_white_background ?? false,
                        'padding_top' => $sourceSection->padding_top,
                        'padding_bottom' => $sourceSection->padding_bottom,
                    ]);
                }
            }
        }
    }

    /**
     * Update sort order for multiple website pages
     */
    public function updateSortOrder()
    {
        \DB::beginTransaction();

        try {
            $request = request();
            $pages = $request->pages ?? [];

            foreach ($pages as $pageData) {
                $decodedId = Hashids::decode($pageData['xid']);
                if (!empty($decodedId)) {
                    WebsitePage::where('id', $decodedId[0])
                        ->update(['sort_order' => $pageData['sort_order']]);
                }
            }

            \DB::commit();

            return response()->json([
                'status' => 'success',
                'message' => 'Sort order updated successfully',
            ]);
        } catch (\Exception $e) {
            \DB::rollBack();

            return response()->json([
                'status' => 'error',
                'message' => 'Failed to update sort order: ' . $e->getMessage(),
            ], 500);
        }
    }
}
