<?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 AdminController {
    protected $request;
    protected $response;
    protected $session;

    public function __construct() {
        $this->request = new Request();
        $this->response = new Response();
        $this->session = new Session();
        
        $user = $this->session->get('admin_user');
        if (!$user || $user['role'] !== 'admin') {
            $currentUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
            $everestBaseUrl = rtrim(str_replace('/cozummerkezi/public', '', $GLOBALS['router']->getBaseUrl()), '/');
            $everestBaseUrl = rtrim(str_replace('/cozummerkezi', '', $everestBaseUrl), '/');
            $everestLoginUrl = $everestBaseUrl . '/admin/login';
            $this->response->redirect($everestLoginUrl . '?return_url=' . urlencode($currentUrl));
        }
    }

    public function dashboard() {
        $totalArticles = count(Article::all());
        $totalCategories = count(Category::all());
        $totalBrands = count(Brand::all());
        $totalCompatibilities = count(Compatibility::all());

        $this->response->render('admin/dashboard', [
            'totalArticles' => $totalArticles,
            'totalCategories' => $totalCategories,
            'totalBrands' => $totalBrands,
            'totalCompatibilities' => $totalCompatibilities,
            'title' => 'Kontrol Paneli'
        ]);
    }

    // ───────────────────────────────────────────────────────
    // ARTICLES CRUD
    // ───────────────────────────────────────────────────────
    public function articles() {
        $articles = Article::all();
        $this->response->render('admin/articles/index', [
            'articles' => $articles,
            'title' => 'Makale ve Reset Yönetimi'
        ]);
    }

    public function articleCreate() {
        $categories = Category::all();
        $brands = Brand::all();
        $this->response->render('admin/articles/create', [
            'categories' => $categories,
            'brands' => $brands,
            'title' => 'Yeni İçerik Ekle'
        ]);
    }

    public function articleStore() {
        $body = $this->request->getBody();
        
        $title = $body['title'] ?? '';
        $slug = !empty($body['slug']) ? $body['slug'] : $this->slugify($title);

        $article = new Article([
            'title' => $title,
            'slug' => $slug,
            'content' => $_POST['content'] ?? '',
            'download_url' => $body['download_url'] ?? '',
            'file_size' => $body['file_size'] ?? '',
            'view_count' => 0,
            'is_featured' => isset($_POST['is_featured']) ? 1 : 0,
            'category_slug' => $body['category_slug'] ?? '',
            'brand_slug' => $body['brand_slug'] ?? '',
            'created_at' => date('Y-m-d H:i:s')
        ]);

        $article->save();
        $this->response->redirect(BASE_URL . '/admin/articles');
    }

    public function articleEdit($id) {
        $article = Article::find($id);
        if (!$article) {
            $this->response->redirect(BASE_URL . '/admin/articles');
        }
        $categories = Category::all();
        $brands = Brand::all();
        $this->response->render('admin/articles/edit', [
            'article' => $article,
            'categories' => $categories,
            'brands' => $brands,
            'title' => 'İçeriği Düzenle'
        ]);
    }

    public function articleUpdate($id) {
        $article = Article::find($id);
        if ($article) {
            $body = $this->request->getBody();
            $title = $body['title'] ?? $article->title;
            $slug = !empty($body['slug']) ? $body['slug'] : $this->slugify($title);

            $article->title = $title;
            $article->slug = $slug;
            $article->content = $_POST['content'] ?? $article->content;
            $article->download_url = $body['download_url'] ?? $article->download_url;
            $article->file_size = $body['file_size'] ?? $article->file_size;
            $article->is_featured = isset($_POST['is_featured']) ? 1 : 0;
            $article->category_slug = $body['category_slug'] ?? $article->category_slug;
            $article->brand_slug = $body['brand_slug'] ?? $article->brand_slug;

            $article->save();
        }
        $this->response->redirect(BASE_URL . '/admin/articles');
    }

    public function articleDelete($id) {
        $article = Article::find($id);
        if ($article) {
            $article->delete();
        }
        $this->response->redirect(BASE_URL . '/admin/articles');
    }

    // ───────────────────────────────────────────────────────
    // CATEGORIES CRUD
    // ───────────────────────────────────────────────────────
    public function categories() {
        $categories = Category::all();
        $this->response->render('admin/categories/index', [
            'categories' => $categories,
            'title' => 'Kategori Yönetimi'
        ]);
    }

    public function categoryCreate() {
        $categories = Category::all(['parent_slug' => null]);
        $this->response->render('admin/categories/create', [
            'categories' => $categories,
            'title' => 'Yeni Kategori Ekle'
        ]);
    }

    public function categoryStore() {
        $body = $this->request->getBody();
        $name = $body['name'] ?? '';
        $slug = !empty($body['slug']) ? $body['slug'] : $this->slugify($name);

        $category = new Category([
            'name' => $name,
            'slug' => $slug,
            'parent_slug' => $body['parent_slug'] !== '' ? $body['parent_slug'] : null
        ]);

        $category->save();
        $this->response->redirect(BASE_URL . '/admin/categories');
    }

    public function categoryEdit($id) {
        $category = Category::find($id);
        if (!$category) {
            $this->response->redirect(BASE_URL . '/admin/categories');
        }
        $categories = Category::all(['parent_slug' => null]);
        $this->response->render('admin/categories/edit', [
            'category' => $category,
            'categories' => $categories,
            'title' => 'Kategori Düzenle'
        ]);
    }

    public function categoryUpdate($id) {
        $category = Category::find($id);
        if ($category) {
            $body = $this->request->getBody();
            $name = $body['name'] ?? $category->name;
            $slug = !empty($body['slug']) ? $body['slug'] : $this->slugify($name);

            $category->name = $name;
            $category->slug = $slug;
            $category->parent_slug = $body['parent_slug'] !== '' ? $body['parent_slug'] : null;

            $category->save();
        }
        $this->response->redirect(BASE_URL . '/admin/categories');
    }

    public function categoryDelete($id) {
        $category = Category::find($id);
        if ($category) {
            $category->delete();
        }
        $this->response->redirect(BASE_URL . '/admin/categories');
    }

    public function categoriesReorder() {
        $body = $this->request->getJsonBody();
        $ids = isset($body['ids']) ? $body['ids'] : [];

        if (empty($ids)) {
            return $this->response->json(['success' => false, 'error' => 'Geçersiz parametre']);
        }

        $db = Category::getDb();
        $categoriesData = $db->selectAll('categories');

        $orderMap = array_flip($ids);
        $toReorder = [];
        foreach ($categoriesData as $cat) {
            if (isset($orderMap[$cat['id']])) {
                $toReorder[] = $cat;
            }
        }

        usort($toReorder, function($a, $b) use ($orderMap) {
            return $orderMap[$a['id']] - $orderMap[$b['id']];
        });

        $reorderedIndex = 0;
        foreach ($categoriesData as &$cat) {
            if (isset($orderMap[$cat['id']])) {
                $cat = $toReorder[$reorderedIndex++];
            }
        }

        $db->saveAll('categories', $categoriesData);
        return $this->response->json(['success' => true]);
    }

    // ───────────────────────────────────────────────────────
    // BRANDS CRUD
    // ───────────────────────────────────────────────────────
    public function brands() {
        $brands = Brand::all();
        $this->response->render('admin/brands/index', [
            'brands' => $brands,
            'title' => 'Marka Yönetimi'
        ]);
    }

    public function brandStore() {
        $body = $this->request->getBody();
        $name = $body['name'] ?? '';
        $slug = !empty($body['slug']) ? $body['slug'] : $this->slugify($name);

        $brand = new Brand([
            'name' => $name,
            'slug' => $slug
        ]);
        $brand->save();
        $this->response->redirect(BASE_URL . '/admin/brands');
    }

    public function brandUpdate($id) {
        $brand = Brand::find($id);
        if ($brand) {
            $body = $this->request->getBody();
            $brand->name = $body['name'] ?? $brand->name;
            $brand->slug = !empty($body['slug']) ? $body['slug'] : $this->slugify($brand->name);
            $brand->save();
        }
        $this->response->redirect(BASE_URL . '/admin/brands');
    }

    public function brandDelete($id) {
        $brand = Brand::find($id);
        if ($brand) {
            $brand->delete();
        }
        $this->response->redirect(BASE_URL . '/admin/brands');
    }

    // ───────────────────────────────────────────────────────
    // COMPATIBILITY CRUD
    // ───────────────────────────────────────────────────────
    public function compatibility() {
        $compatibilities = Compatibility::all();
        $this->response->render('admin/compatibility/index', [
            'compatibilities' => $compatibilities,
            'title' => 'Uyumluluk Tabloları'
        ]);
    }

    public function compatibilityCreate() {
        $this->response->render('admin/compatibility/create', [
            'title' => 'Yeni Uyumluluk Tablosu Ekle'
        ]);
    }

    public function compatibilityStore() {
        $body = $this->request->getBody();
        $title = $body['title'] ?? '';
        $slug = !empty($body['slug']) ? $body['slug'] : $this->slugify($title);

        $headersRaw = $_POST['headers'] ?? '';
        $headers = array_map('trim', explode(',', $headersRaw));

        $rowsRaw = $_POST['rows'] ?? '';
        $rows = [];
        $lines = explode("\n", str_replace("\r", "", $rowsRaw));
        foreach ($lines as $line) {
            if (trim($line) !== '') {
                $rows[] = array_map('trim', explode('|', $line));
            }
        }

        $comp = new Compatibility([
            'title' => $title,
            'slug' => $slug,
            'headers' => $headers,
            'rows' => $rows
        ]);
        $comp->save();
        $this->response->redirect(BASE_URL . '/admin/compatibility');
    }

    public function compatibilityEdit($slug) {
        $comp = Compatibility::findBy(['slug' => $slug]);
        if (!$comp) {
            $this->response->redirect(BASE_URL . '/admin/compatibility');
        }

        $headersStr = implode(', ', $comp->headers ?? []);
        
        $rowsLines = [];
        foreach ($comp->rows ?? [] as $row) {
            $rowsLines[] = implode(' | ', $row);
        }
        $rowsStr = implode("\n", $rowsLines);

        $this->response->render('admin/compatibility/edit', [
            'comp' => $comp,
            'headersStr' => $headersStr,
            'rowsStr' => $rowsStr,
            'title' => 'Uyumluluk Tablosu Düzenle'
        ]);
    }

    public function compatibilityUpdate($slug) {
        $comp = Compatibility::findBy(['slug' => $slug]);
        if ($comp) {
            $body = $this->request->getBody();
            $comp->title = $body['title'] ?? $comp->title;
            $comp->slug = !empty($body['slug']) ? $body['slug'] : $this->slugify($comp->title);

            $headersRaw = $_POST['headers'] ?? '';
            $comp->headers = array_map('trim', explode(',', $headersRaw));

            $rowsRaw = $_POST['rows'] ?? '';
            $rows = [];
            $lines = explode("\n", str_replace("\r", "", $rowsRaw));
            foreach ($lines as $line) {
                if (trim($line) !== '') {
                    $rows[] = array_map('trim', explode('|', $line));
                }
            }
            $comp->rows = $rows;
            $comp->save();
        }
        $this->response->redirect(BASE_URL . '/admin/compatibility');
    }

    public function compatibilityDelete($slug) {
        $comp = Compatibility::findBy(['slug' => $slug]);
        if ($comp) {
            $comp->delete();
        }
        $this->response->redirect(BASE_URL . '/admin/compatibility');
    }

    // ───────────────────────────────────────────────────────
    // SETTINGS CRUD
    // ───────────────────────────────────────────────────────
    public function settings() {
        $settings = Settings::all();
        $this->response->render('admin/settings', [
            'settings' => $settings,
            'title' => 'Sistem Ayarları'
        ]);
    }

    public function settingsUpdate() {
        $body = $this->request->getBody();
        
        $logoImage = $_POST['existing_logo'] ?? '';
        
        // Handle file upload
        if (isset($_FILES['logo_upload']) && $_FILES['logo_upload']['error'] === UPLOAD_ERR_OK) {
            $uploadDir = __DIR__ . '/../../public/uploads/logos/';
            if (!is_dir($uploadDir)) {
                mkdir($uploadDir, 0777, true);
            }
            
            $fileTmp = $_FILES['logo_upload']['tmp_name'];
            $fileName = time() . '_' . basename($_FILES['logo_upload']['name']);
            $targetPath = $uploadDir . $fileName;
            
            if (move_uploaded_file($fileTmp, $targetPath)) {
                $logoImage = BASE_URL . '/uploads/logos/' . $fileName;
            }
        }

        Settings::updateAll([
            'store_title' => $body['store_title'] ?? '',
            'store_description' => $body['store_description'] ?? '',
            'telephone' => $body['telephone'] ?? '',
            'mobile' => $body['mobile'] ?? '',
            'email' => $body['email'] ?? '',
            'address' => $body['address'] ?? '',
            'maintenance_mode' => isset($_POST['maintenance_mode']) ? "1" : "0",
            'logo_type' => $body['logo_type'] ?? 'text',
            'logo_image' => $logoImage,
            'logo_text_main' => $body['logo_text_main'] ?? 'Çözüm',
            'logo_text_highlight' => $body['logo_text_highlight'] ?? 'Merkezi',
            'logo_slogan' => $body['logo_slogan'] ?? 'Yazıcı Teknik Servis Çözümleri'
        ]);
        $this->response->redirect(BASE_URL . '/admin/settings');
    }

    // Helpers
    protected function slugify($text) {
        $find =    ['Ç', 'Ş', 'Ğ', 'Ü', 'İ', 'Ö', 'ç', 'ş', 'ğ', 'ü', 'ı', 'ö'];
        $replace = ['c', 's', 'g', 'u', 'i', 'o', 'c', 's', 'g', 'u', 'i', 'o'];
        $text = str_replace($find, $replace, $text);
        $text = preg_replace('~[^\pL\d]+~u', '-', $text);
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
        $text = preg_replace('~[^-\w]+~', '', $text);
        $text = trim($text, '-');
        $text = preg_replace('~-+~', '-', $text);
        $text = strtolower($text);
        if (empty($text)) {
            return 'n-a';
        }
        return $text;
    }
}
