<?php

namespace Core\App\Controllers;

use Core\App\Models\CategoryModel;
use Core\App\Models\HomeSections;
use Core\App\Models\ProductModel;
use Core\System\Response;
use Core\System\SeoManager;
use Core\System\ThemeManager;

class HomeController
{
    public function index()
    {
        SeoManager::fromHome();
        SeoManager::addWebsiteSchema();

        $homeSectionsModel = new HomeSections();
        $homeSections = $homeSectionsModel->getAll();
        $productModel = new ProductModel();

        $forceShowAll = isset($_GET['show_all_products']) && (int)$_GET['show_all_products'] === 1;
        foreach ($homeSections as &$section) {
            if ($section['section_type'] !== 'products_section') {
                continue;
            }

            if ($forceShowAll) {
                $section['products'] = $productModel->getForHome();
                continue;
            }

            $settings = $section['settings'] ?? [];
            $source = $settings['source'] ?? 'latest';
            if ($source === 'featured') {
                $section['products'] = $productModel->getFeaturedForHome();
            } elseif ($source === 'category' && !empty($settings['category_id'])) {
                $section['products'] = $productModel->getByCategoryForHome((int)$settings['category_id']);
            } else {
                $section['products'] = $productModel->getForHome();
            }
        }

        ThemeManager::render('home', ['home_sections' => $homeSections]);
    }

   public function product($identifier)
{
    $productModel = new ProductModel();
    $identifier = trim(rawurldecode((string) $identifier));

    $product = ctype_digit($identifier)
        ? $productModel->getById((int) $identifier)
        : $productModel->getBySlug($identifier);

    if (!$product || (($product['status'] ?? 'active') !== 'active')) {
        http_response_code(404);
        ThemeManager::render('404');
        return;
    }

    $canonicalIdentifier = !empty($product['slug'])
        ? (string) $product['slug']
        : (string) (int) $product['id'];

    $canonicalPath = '/product/' . rawurlencode($canonicalIdentifier);

    if ($identifier !== $canonicalIdentifier) {
        // 301 so search engines consolidate link equity to the canonical slug URL
        Response::permanentRedirect($canonicalPath);
        return;
    }

    SeoManager::fromProduct($product);
    ThemeManager::render('product', ['product' => $product]);
}

    public function products()
    {
        $page = max(1, (int)($_GET['page'] ?? 1));
        $q = trim((string)($_GET['q'] ?? ''));
        $productModel = new ProductModel();
        $result = $productModel->getActivePaginated($page, 12, $q);
        $querySuffix = $q !== '' ? ('?q=' . rawurlencode($q) . ($page > 1 ? '&page=' . $page : '')) : ($page > 1 ? '?page=' . $page : '');

        SeoManager::set([
            'type' => 'products_archive',
            'title' => ($q !== '' ? __('actions.search', 'Search') . ': ' . $q : __('products.archive_title', 'Products')) . ' | ' . ThemeManager::getSetting('site_name', 'Website'),
            'description' => $q !== '' ? __('search.placeholder', 'What are you looking for?') . ' ' . $q : __('products.archive_description', 'Browse our latest products.'),
            'canonical' => SeoManager::absoluteUrl(url('/products' . $querySuffix)),
        ]);

        ThemeManager::render('products_archive', [
            'products' => $result['items'],
            'pagination' => $result,
            'archive_title' => $q !== '' ? __('actions.search', 'Search') . ': ' . $q : __('products.archive_title', 'Products'),
            'archive_description' => $q !== '' ? __('search.placeholder', 'What are you looking for?') : __('products.archive_description', 'Browse our latest products.'),
            'canonicalBase' => '/products' . ($q !== '' ? ('?q=' . rawurlencode($q)) : ''),
            'search_query' => $q,
        ]);
    }

    public function category($slug)
    {
        $page = max(1, (int)($_GET['page'] ?? 1));
        $category = (new CategoryModel())->getBySlug((string)$slug);
        if (!$category) {
            http_response_code(404);
            ThemeManager::render('404');
            return;
        }

        $result = (new ProductModel())->getByCategorySlugPaginated($category['slug'], $page, 12);
        SeoManager::set([
            'type' => 'category_archive',
            'title' => trim(($category['name'] ?? __('categories.title', 'Category')) . ' | ' . ThemeManager::getSetting('site_name', 'Website')),
            'description' => trim((string)($category['meta_description'] ?? __('categories.archive_description', 'Browse products in this category.'))),
            'canonical' => SeoManager::absoluteUrl(url('/category/' . $category['slug'] . ($page > 1 ? '?page=' . $page : ''))),
        ]);

        ThemeManager::render('products_archive', [
            'products' => $result['items'],
            'pagination' => $result,
            'archive_title' => $category['name'] ?? __('categories.title', 'Category'),
            'archive_description' => __('categories.archive_description', 'Browse products in this category.'),
            'canonicalBase' => '/category/' . $category['slug'],
            'category' => $category,
        ]);
    }


    public function homeSearch()
    {
        $q = trim((string)($_GET['q'] ?? ''));

        header('Content-Type: text/html; charset=UTF-8');
        header('X-Robots-Tag: noindex, nofollow', true);

        if ($q === '') {
            echo '';
            return;
        }

        $context = $this->getHomeProductsSectionContext();
        $products = (new ProductModel())->searchForHome(
            $q,
            48,
            $context['source'],
            $context['category_id']
        );

        echo $this->renderHomeProductCards($products);
    }

    private function getHomeProductsSectionContext(): array
    {
        $homeSections = (new HomeSections())->getAll();

        foreach ($homeSections as $section) {
            if (($section['section_type'] ?? '') !== 'products_section') {
                continue;
            }

            $settings = $section['settings'] ?? [];
            $source = (string)($settings['source'] ?? 'latest');
            $categoryId = isset($settings['category_id']) ? (int)$settings['category_id'] : null;

            return [
                'source' => in_array($source, ['latest', 'featured', 'category'], true) ? $source : 'latest',
                'category_id' => ($source === 'category' && $categoryId && $categoryId > 0) ? $categoryId : null,
            ];
        }

        return [
            'source' => 'latest',
            'category_id' => null,
        ];
    }

    private function renderHomeProductCards(array $products): string
    {
        $settingsModel = new \Core\App\Models\Settings();
        $__cardAutoRotate = (int)$settingsModel->get('product_image_autorotate', 1);
        $__badgePresets = [
            'products.badge_preset_new'       => ['class' => 'badge-new', 'emoji' => '✨', 'fallback' => 'New Arrival'],
            'products.badge_preset_hot'       => ['class' => 'badge-hot', 'emoji' => '🔥', 'fallback' => 'Best Seller'],
            'products.badge_preset_sale'      => ['class' => 'badge-sale', 'emoji' => '🎁', 'fallback' => 'Special Offer'],
            'products.badge_preset_limited'   => ['class' => 'badge-limited', 'emoji' => '⏳', 'fallback' => 'Limited Stock'],
            'products.badge_preset_exclusive' => ['class' => 'badge-exclusive', 'emoji' => '💎', 'fallback' => 'Exclusive'],
            'products.badge_preset_shipping'  => ['class' => 'badge-shipping', 'emoji' => '🚚', 'fallback' => 'Free Shipping'],
            'products.badge_preset_discount'  => ['class' => 'badge-discount', 'emoji' => '🏷️', 'fallback' => 'Discount'],
        ];
        $__badgeLegacyMap = [
            'وصل حديثًا' => 'products.badge_preset_new', 'الأكثر مبيعًا' => 'products.badge_preset_hot',
            'عرض خاص' => 'products.badge_preset_sale', 'كمية محدودة' => 'products.badge_preset_limited',
            'حصري' => 'products.badge_preset_exclusive', 'توصيل مجاني' => 'products.badge_preset_shipping',
            'تخفيض' => 'products.badge_preset_discount', 'New Arrival' => 'products.badge_preset_new',
            'Best Seller' => 'products.badge_preset_hot', 'Special Offer' => 'products.badge_preset_sale',
            'Limited Stock' => 'products.badge_preset_limited', 'Exclusive' => 'products.badge_preset_exclusive',
            'Free Shipping' => 'products.badge_preset_shipping', 'Discount' => 'products.badge_preset_discount',
            'new' => 'products.badge_preset_new', 'hot' => 'products.badge_preset_hot', 'sale' => 'products.badge_preset_sale',
            'limited' => 'products.badge_preset_limited', 'exclusive' => 'products.badge_preset_exclusive',
            'free_shipping' => 'products.badge_preset_shipping', 'discount' => 'products.badge_preset_discount'
        ];
        $__productCardsMarkupFile = ROOT_PATH . '/themes/matjari/home_sections/partials/product_cards_markup.php';

        ob_start();
        include $__productCardsMarkupFile;
        return (string)ob_get_clean();
    }

}
