<?php
namespace App\Controllers;

use App\Core\Request;
use App\Core\Response;
use App\Core\Session;
use App\Models\Category;
use App\Models\Brand;
use App\Models\Article;
use App\Models\Compatibility;
use App\Models\Settings;

class ClientController {
    protected $request;
    protected $response;
    protected $session;

    public function __construct() {
        $this->request = new Request();
        $this->response = new Response();
        $this->session = new Session();
    }

    public function home() {
        $brands = Brand::all();
        $categories = Category::all(['parent_slug' => null]);
        $featuredArticles = Article::all(['is_featured' => 1]);
        $allArticles = Article::all();
        $compatibilities = Compatibility::all();
        usort($compatibilities, function($a, $b) {
            return ($b->view_count ?? 0) <=> ($a->view_count ?? 0);
        });

        $this->response->render('client/home', [
            'brands' => $brands,
            'categories' => $categories,
            'featuredArticles' => $featuredArticles,
            'allArticles' => $allArticles,
            'compatibilities' => $compatibilities,
            'title' => Settings::get('store_title')
        ]);
    }

    public function search() {
        $q = trim($_GET['q'] ?? '');
        $allArticles = Article::all();
        $results = [];

        if ($q !== '') {
            $qLower = mb_strtolower($q, 'UTF-8');
            foreach ($allArticles as $art) {
                $title = mb_strtolower($art->title, 'UTF-8');
                $content = mb_strtolower($art->content, 'UTF-8');
                if (strpos($title, $qLower) !== false || strpos($content, $qLower) !== false) {
                    $results[] = $art;
                }
            }
        }

        $this->response->render('client/search', [
            'query' => $q,
            'results' => $results,
            'title' => '"' . htmlspecialchars($q) . '" Arama Sonuçları'
        ]);
    }

    public function apiSearch() {
        header('Content-Type: application/json; charset=utf-8');
        $q = trim($_GET['q'] ?? '');
        $results = [];

        if ($q !== '') {
            $qLower = mb_strtolower($q, 'UTF-8');
            
            // Search Articles
            $allArticles = Article::all();
            foreach ($allArticles as $art) {
                $title = mb_strtolower($art->title, 'UTF-8');
                if (strpos($title, $qLower) !== false) {
                    $results[] = [
                        'title' => $art->title,
                        'slug' => $art->slug,
                        'type' => 'Kılavuz'
                    ];
                }
            }
            
            // Search Compatibilities
            $allComps = Compatibility::all();
            foreach ($allComps as $comp) {
                $title = mb_strtolower($comp->title, 'UTF-8');
                if (strpos($title, $qLower) !== false) {
                    $results[] = [
                        'title' => $comp->title,
                        'slug' => $comp->slug,
                        'type' => 'Uyumluluk Tablosu'
                    ];
                }
            }
            
            // Limit results for UI performance
            $results = array_slice($results, 0, 8);
        }

        echo json_encode($results, JSON_UNESCAPED_UNICODE);
        exit;
    }

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

    public function compatibilities() {
        $compatibilities = Compatibility::all();
        usort($compatibilities, function($a, $b) {
            return ($b->view_count ?? 0) <=> ($a->view_count ?? 0);
        });
        $slug = $_GET['table'] ?? '';
        $selectedTable = null;

        if ($slug !== '') {
            $selectedTable = Compatibility::findBy(['slug' => $slug]);
        }

        $this->response->render('client/compatibilities', [
            'compatibilities' => $compatibilities,
            'selectedTable' => $selectedTable,
            'title' => 'Parça Uyumluluk Tabloları'
        ]);
    }

    public function brands() {
        $brands = Brand::all();
        $this->response->render('client/brands', [
            'brands' => $brands,
            'title' => 'Markalar'
        ]);
    }

    public function resolveSlug($slug, $fullPath) {
        $slug = urldecode($slug);
        
        // 1. Try Article
        $article = Article::findBy(['slug' => $slug]);
        if ($article) {
            $article->view_count = ($article->view_count ?? 0) + 1;
            $article->save();
            
            return $this->response->render('client/article_detail', [
                'article' => $article,
                'title' => $article->title . ' - Çözüm Merkezi'
            ]);
        }

        // 2. Try Category
        $category = Category::findBy(['slug' => $slug]);
        if ($category) {
            $articles = Article::all(['category_slug' => $category->slug]);
            return $this->response->render('client/category_detail', [
                'category' => $category,
                'articles' => $articles,
                'title' => $category->name . ' Çözümleri'
            ]);
        }

        // 3. Try Compatibility
        $comp = Compatibility::findBy(['slug' => $slug]);
        if ($comp) {
            $comp->view_count = ($comp->view_count ?? 0) + 1;
            $comp->updateBy(['slug' => $slug]);

            return $this->response->render('client/compatibility_detail', [
                'table' => $comp,
                'title' => $comp->title
            ]);
        }

        // 4. Try Brand
        $brand = Brand::findBy(['slug' => $slug]);
        if ($brand) {
            $articles = Article::all(['brand_slug' => $brand->slug]);
            return $this->response->render('client/brand_detail', [
                'brand' => $brand,
                'articles' => $articles,
                'title' => $brand->name . ' Reset ve Hata Çözümleri'
            ]);
        }

        $this->notFound();
    }

    public function notFound() {
        $this->response->setStatusCode(404);
        $this->response->render('client/404', [
            'title' => 'Sayfa Bulunamadı - Çözüm Merkezi'
        ]);
    }
}
