<?php
namespace App\Controllers;

use App\Models\Product;
use App\Models\Category;
use App\Models\Settings;
use App\Services\CurrencyService;

class ClientController extends Controller {

    public function home() {
        $categories = Category::all(['parent_slug' => null]);

        $allActive = Product::all(['status' => 1]);
        $featured = [];
        $others = [];
        foreach ($allActive as $p) {
            if (!empty($p->featured)) {
                $featured[] = $p;
            } else {
                $others[] = $p;
            }
        }

        // If no featured products exist, fall back to first 5 active
        if (empty($featured)) {
            $featured = array_slice($allActive, 0, 5);
            $others = array_slice($allActive, 5);
        }

        $this->response->render('client/home', [
            'categories' => $categories,
            'featuredProducts' => $featured,
            'otherProducts' => $others,
            'title' => Settings::get('store_title')
        ]);
    }

    public function resolveSlug($slug, $fullPath) {
        // Decode URL components for Turkish characters
        $slug = urldecode($slug);
        $fullPath = urldecode($fullPath);
        
        // 1. Try to find a Product where slug equals fullPath, or ends with /$slug
        $product = null;
        $allProducts = Product::all(['status' => 1]);
        foreach ($allProducts as $p) {
            if ($p->slug === $fullPath || $p->slug === $slug || 
                (strpos($p->slug, '/') !== false && basename($p->slug) === $slug)) {
                $product = $p;
                break;
            }
        }

        if ($product) {
            return $this->product($product);
        }

        // 2. Try to find a Category
        $category = null;
        $allCategories = Category::all();
        foreach ($allCategories as $c) {
            if ($c->slug === $fullPath || $c->slug === $slug || 
                (strpos($c->slug, '/') !== false && basename($c->slug) === $slug)) {
                $category = $c;
                break;
            }
        }

        if ($category) {
            return $this->category($category);
        }

        // 3. Static Page redirection or default routing checks
        // Check legacy brand URLs
        $settings = Settings::all();
        $brands = isset($settings['brands']) ? $settings['brands'] : [];
        foreach ($brands as $b) {
            if ($b['slug'] === $fullPath || $b['slug'] === $slug) {
                return $this->brand($b);
            }
        }

        // 4. Contact page fallback
        if ($slug === 'contact' || $fullPath === 'information/contact') {
            return $this->contact();
        }

        // 5. Custom static pages
        $staticPages = [
            'hizli-kargo', 'guvenli-odeme', 'teknik-destek', 'hp-hata-kodları',
            'hakkimizda', 'gizlilik-politikasi', 'cerez-politikasi',
            'mesafeli-satis-sozlesmesi', 'iade-politikasi', 'kvkk'
        ];
        if (in_array($slug, $staticPages)) {
            return $this->staticPage($slug);
        }

        // Send 404 if no matches found
        header("HTTP/1.0 404 Not Found");
        $this->response->render('client/404', [
            'title' => 'Sayfa Bulunamadı - 404'
        ]);
    }

    protected function product($product) {
        $categories = Category::all(['parent_slug' => null]);
        
        $this->response->render('client/product', [
            'product' => $product,
            'categories' => $categories,
            'title' => $product->name . ' - ' . Settings::get('store_name')
        ]);
    }

    protected function category($category) {
        $categories = Category::all(['parent_slug' => null]);
        $subcategories = $category->getSubcategories();

        $perPage = 20;
        $page = max(1, (int)($_GET['page'] ?? 1));
        $allProducts = $category->getProducts();
        $total = count($allProducts);
        $totalPages = max(1, (int)ceil($total / $perPage));
        $products = array_slice($allProducts, ($page - 1) * $perPage, $perPage);

        $this->response->render('client/category', [
            'category' => $category,
            'categories' => $categories,
            'subcategories' => $subcategories,
            'products' => $products,
            'page' => $page,
            'totalPages' => $totalPages,
            'total' => $total,
            'title' => $category->name . ' - ' . Settings::get('store_name')
        ]);
    }

    protected function brand($brand) {
        $categories = Category::all(['parent_slug' => null]);

        $perPage = 20;
        $page = max(1, (int)($_GET['page'] ?? 1));
        $allProducts = Product::all(['status' => 1, 'brand_slug' => $brand['slug']]);
        $total = count($allProducts);
        $totalPages = max(1, (int)ceil($total / $perPage));
        $products = array_slice($allProducts, ($page - 1) * $perPage, $perPage);

        $this->response->render('client/brand', [
            'brand' => $brand,
            'categories' => $categories,
            'products' => $products,
            'page' => $page,
            'totalPages' => $totalPages,
            'total' => $total,
            'title' => $brand['name'] . ' Ürünleri - ' . Settings::get('store_name')
        ]);
    }

    public function brandsPage() {
        $categories = Category::all(['parent_slug' => null]);
        $settings = Settings::all();
        $brands = isset($settings['brands']) ? $settings['brands'] : [];

        $this->response->render('client/brands', [
            'categories' => $categories,
            'brands' => $brands,
            'title' => 'Markalar - ' . Settings::get('store_name')
        ]);
    }

    public function search() {
        $q = isset($_GET['q']) ? trim($_GET['q']) : '';
        $filter = isset($_GET['filter']) ? $_GET['filter'] : '';
        
        $categories = Category::all(['parent_slug' => null]);
        $allProducts = Product::all(['status' => 1]);

        if ($q !== '') {
            $matched = [];
            foreach ($allProducts as $p) {
                if (stripos($p->name, $q) !== false || stripos($p->model, $q) !== false || stripos($p->description, $q) !== false) {
                    $matched[] = $p;
                }
            }
            $allProducts = $matched;
        }

        if ($filter === 'featured') {
            $filtered = [];
            foreach ($allProducts as $p) {
                if (!empty($p->featured)) {
                    $filtered[] = $p;
                }
            }
            $allProducts = !empty($filtered) ? $filtered : array_slice($allProducts, 0, 5);
        } elseif ($filter === 'new') {
            $filtered = [];
            foreach ($allProducts as $p) {
                if (empty($p->featured)) {
                    $filtered[] = $p;
                }
            }
            $allProducts = !empty($filtered) ? $filtered : array_slice($allProducts, 5);
        }

        $pageTitle = 'Tüm Ürünler';
        if ($q !== '') {
            $pageTitle = $q;
        } elseif ($filter === 'featured') {
            $pageTitle = 'En Çok Tercih Edilenler';
        } elseif ($filter === 'new') {
            $pageTitle = 'Yeni Ürünler';
        }

        $perPage = 20;
        $page = max(1, (int)($_GET['page'] ?? 1));
        $total = count($allProducts);
        $totalPages = max(1, (int)ceil($total / $perPage));
        $products = array_slice($allProducts, ($page - 1) * $perPage, $perPage);

        $this->response->render('client/search', [
            'q' => $q,
            'categories' => $categories,
            'products' => $products,
            'page' => $page,
            'totalPages' => $totalPages,
            'total' => $total,
            'title' => $pageTitle . ' - ' . Settings::get('store_name')
        ]);
    }

    public function contact() {
        $categories = Category::all(['parent_slug' => null]);
        $this->response->render('client/contact', [
            'categories' => $categories,
            'title' => 'İletişim - ' . Settings::get('store_name')
        ]);
    }

    protected function staticPage($slug) {
        $categories = Category::all(['parent_slug' => null]);
        
        $page = \App\Models\Page::findBySlug($slug);
        
        if (!$page) {
            $GLOBALS['router']->send404();
        }

        $allPages = \App\Models\Page::all();

        $this->response->render('client/page', [
            'categories' => $categories,
            'pageTitle' => $page->title,
            'content' => $page->content,
            'allPages' => $allPages,
            'currentSlug' => $slug,
            'title' => $page->title . ' - ' . Settings::get('store_name')
        ]);
    }


}
