<?php
namespace App\Controllers;

use App\Models\Product;
use App\Models\Category;
use App\Models\Order;
use App\Models\User;
use App\Models\Settings;
use App\Models\Page;
use App\Services\ImageService;

/**
 * Helper: get brand image URL from user upload or fallback to generated one
 */
function brandImageUrl($brand, $baseUrl) {
    if (!empty($brand['image'])) {
        return $baseUrl . '/' . ltrim($brand['image'], '/');
    }
    $path = __DIR__ . '/../../public/uploads/brands/' . $brand['slug'] . '.webp';
    if (file_exists($path)) {
        return $baseUrl . '/uploads/brands/' . $brand['slug'] . '.webp';
    }
    return '';
}

class AdminController extends Controller {

    public function __construct() {
        parent::__construct();
        
        $uri = $_SERVER['REQUEST_URI'];
        if (($pos = strpos($uri, '?')) !== false) {
            $uri = substr($uri, 0, $pos);
        }
        $uri = rtrim($uri, '/');
        
        $isLoginOrAuth = (str_ends_with($uri, '/admin/login') || str_ends_with($uri, '/admin/auth'));
        
        if (!$isLoginOrAuth) {
            $user = $this->session->get('admin_user');
            if (!$user || $user['role'] !== 'admin') {
                $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/login');
            }
        }
    }

    public function login() {
        if (isset($_GET['return_url']) && !empty($_GET['return_url'])) {
            $this->session->set('admin_return_url', $_GET['return_url']);
        }

        if ($this->session->get('admin_user')) {
            $returnUrl = $this->session->get('admin_return_url');
            if ($returnUrl) {
                $this->session->remove('admin_return_url');
                $this->response->redirect($returnUrl);
                return;
            }
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/dashboard');
            return;
        }
        $this->response->render('admin/login', [
            'title' => 'Yönetici Girişi - Everest Büro Makinaları'
        ]);
    }

    public function auth() {
        $body = $this->request->getBody();
        $username = isset($body['username']) ? $body['username'] : '';
        $password = isset($body['password']) ? $body['password'] : '';

        $user = User::findBy(['username' => $username]);

        if ($user && $user->verifyPassword($password) && $user->role === 'admin') {
            $this->session->set('admin_user', [
                'id' => $user->id,
                'username' => $user->username,
                'name' => $user->name,
                'role' => $user->role,
                'avatar' => $user->avatar
            ]);
            
            $returnUrl = $this->session->get('admin_return_url');
            if ($returnUrl) {
                $this->session->remove('admin_return_url');
                $this->response->redirect($returnUrl);
                return;
            }
            
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/dashboard');
            return;
        }

        $this->response->render('admin/login', [
            'error' => 'Geçersiz kullanıcı adı veya şifre.',
            'title' => 'Yönetici Girişi - Everest Büro Makinaları'
        ]);
    }

    public function logout() {
        $this->session->remove('admin_user');
        $this->session->remove('customer_user');
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/login');
    }

    public function dashboard() {
        $products = Product::all();
        $categories = Category::all();
        $orders = Order::all();

        $this->response->render('admin/dashboard', [
            'productsCount' => count($products),
            'categoriesCount' => count($categories),
            'ordersCount' => count($orders),
            'orders' => array_slice(array_reverse($orders), 0, 5),
            'title' => 'Yönetim Paneli - Everest Büro Makinaları'
        ]);
    }

    // Products CRUD
    public function products() {
        $products = Product::all();

        // Search filter (name, model, brand)
        $search = trim($_GET['search'] ?? '');
        if ($search !== '') {
            $searchLower = mb_strtolower($search, 'UTF-8');
            $settings = Settings::all();
            $allBrands = isset($settings['brands']) ? $settings['brands'] : [];
            $products = array_values(array_filter($products, function($p) use ($searchLower, $allBrands) {
                $name = mb_strtolower($p->name ?? '', 'UTF-8');
                $model = mb_strtolower($p->model ?? '', 'UTF-8');
                // Look up brand name
                $brandName = '';
                foreach ($allBrands as $b) {
                    if ($b['slug'] === ($p->brand_slug ?? '')) {
                        $brandName = mb_strtolower($b['name'] ?? '', 'UTF-8');
                        break;
                    }
                }
                return strpos($name, $searchLower) !== false || strpos($model, $searchLower) !== false || strpos($brandName, $searchLower) !== false;
            }));
        }

        // Sorting
        $sort = $_GET['sort'] ?? '';
        $order = $_GET['order'] ?? 'desc';
        $allowedSort = ['name', 'model', 'price', 'stock', 'status', 'featured', 'brand_slug'];

        if ($sort === '' || !in_array($sort, $allowedSort)) {
            $products = array_reverse($products);
        } else {
            usort($products, function($a, $b) use ($sort, $order) {
                $va = $a->$sort ?? '';
                $vb = $b->$sort ?? '';
                if (is_numeric($va) && is_numeric($vb)) {
                    return $order === 'asc' ? $va <=> $vb : $vb <=> $va;
                }
                $va = mb_strtolower((string)$va, 'UTF-8');
                $vb = mb_strtolower((string)$vb, 'UTF-8');
                return $order === 'asc' ? strcmp($va, $vb) : strcmp($vb, $va);
            });
        }

        $perPage = 20;
        $total = count($products);
        $totalPages = max(1, (int)ceil($total / $perPage));
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;

        if ($page < 1) $page = 1;
        if ($page > $totalPages) $page = $totalPages;

        $offset = ($page - 1) * $perPage;
        $paginatedProducts = array_slice($products, $offset, $perPage);

        $settings = Settings::all();
        $brands = isset($settings['brands']) ? $settings['brands'] : [];

        $this->response->render('admin/products/index', [
            'products' => $paginatedProducts,
            'currentPage' => $page,
            'totalPages' => $totalPages,
            'totalProducts' => $total,
            'search' => $search,
            'sort' => $sort,
            'order' => $order,
            'brands' => $brands,
            'title' => 'Ürün Yönetimi - Yönetim Paneli'
        ]);
    }

    public function productUpdateFieldAjax($id) {
        $product = Product::find($id);
        if (!$product) {
            $this->response->json(['success' => false, 'message' => 'Ürün bulunamadı.']);
            return;
        }

        $body = $this->request->getJsonBody();
        if (empty($body) || !isset($body['field']) || !isset($body['value'])) {
            $this->response->json(['success' => false, 'message' => 'Geçersiz veri.']);
            return;
        }

        $field = $body['field'];
        $value = $body['value'];

        $allowedFields = ['name', 'model', 'price', 'stock'];
        if (!in_array($field, $allowedFields)) {
            $this->response->json(['success' => false, 'message' => 'Bu alan güncellenemez.']);
            return;
        }

        if ($field === 'price') {
            $product->price = (float)$value;
            $product->save();
            $this->response->json([
                'success' => true,
                'newValue' => $product->price,
                'newFormatted' => $product->getOriginalPriceFormatted()
            ]);
        } else if ($field === 'stock') {
            $product->stock = (int)$value;
            $product->save();
            $this->response->json([
                'success' => true,
                'newValue' => $product->stock,
                'newFormatted' => $product->stock
            ]);
        } else {
            // String fields like name, model
            $product->$field = trim($value);
            $product->save();
            $this->response->json([
                'success' => true,
                'newValue' => $product->$field,
                'newFormatted' => htmlspecialchars($product->$field)
            ]);
        }
    }

    public function productToggleFeatured($id) {
        $product = Product::find($id);
        if (!$product) {
            $this->response->json(['success' => false, 'message' => 'Ürün bulunamadı.']);
            return;
        }
        $current = (int)($product->featured ?? 0);
        $new = $current ? 0 : 1;
        $product->featured = $new;
        $product->save();
        $this->response->json([
            'success' => true,
            'featured' => $new,
        ]);
    }

    public function productBulkAction() {
        $body = $this->request->getJsonBody();
        if (empty($body) || !isset($body['action']) || !isset($body['ids']) || !is_array($body['ids'])) {
            $this->response->json(['success' => false, 'message' => 'Geçersiz veri.']);
            return;
        }

        $action = $body['action'];
        $ids = $body['ids'];
        $updatedCount = 0;

        foreach ($ids as $id) {
            $product = Product::find($id);
            if ($product) {
                if ($action === 'delete') {
                    $product->delete();
                    $updatedCount++;
                } else if ($action === 'status_active') {
                    $product->status = 1;
                    $product->save();
                    $updatedCount++;
                } else if ($action === 'status_inactive') {
                    $product->status = 0;
                    $product->save();
                    $updatedCount++;
                }
            }
        }

        $this->response->json(['success' => true, 'updatedCount' => $updatedCount]);
    }

    public function productCreate() {
        $categories = Category::all();
        $this->response->render('admin/products/create', [
            'categories' => $categories,
            'title' => 'Yeni Ürün Ekle - Yönetim Paneli'
        ]);
    }

    public function productStore() {
        $body = $this->request->getBody();
        
        // Parse checkboxes for categories
        $categoriesChecked = isset($_POST['categories']) ? $_POST['categories'] : [];
        
        $name = isset($body['name']) ? $body['name'] : '';
        $slug = !empty($body['slug']) ? $this->slugify($body['slug']) : $this->slugify($name);

        $imageService = new ImageService('products');
        $uploadedImages = [];
        $uploadedFilesAssoc = [];
        if (!empty($_FILES['images'])) {
            $uploadedFilesAssoc = $imageService->uploadMultiple($_FILES['images']);
            $uploadedImages = array_merge($uploadedImages, array_values($uploadedFilesAssoc));
        }
        if (!empty($_POST['image_urls'])) {
            $uploadedImages = array_merge($uploadedImages, $imageService->fetchFromUrls($_POST['image_urls']));
        }

        $mainImage = isset($_POST['main_image']) ? $_POST['main_image'] : null;
        if ($mainImage) {
            $mainImagePath = null;
            if (strpos($mainImage, 'new::') === 0) {
                $filename = substr($mainImage, 5);
                if (isset($uploadedFilesAssoc[$filename])) {
                    $mainImagePath = $uploadedFilesAssoc[$filename];
                }
            } elseif (strpos($mainImage, 'existing::') === 0) {
                $mainImagePath = substr($mainImage, 10);
            }
            
            if ($mainImagePath && ($key = array_search($mainImagePath, $uploadedImages)) !== false) {
                unset($uploadedImages[$key]);
                array_unshift($uploadedImages, $mainImagePath);
                $uploadedImages = array_values($uploadedImages);
            }
        }

        $product = new Product([
            'name' => $name,
            'slug' => $slug,
            'model' => isset($body['model']) ? $body['model'] : '',
            'brand_slug' => isset($body['brand_slug']) ? $body['brand_slug'] : '',
            'price' => (float)(isset($body['price']) ? $body['price'] : 0.0),
            'currency' => isset($body['currency']) ? $body['currency'] : 'TRY',
            'stock' => (int)(isset($body['stock']) ? $body['stock'] : 10),
            'description' => isset($_POST['description']) ? $_POST['description'] : '',
            'categories' => json_encode($categoriesChecked),
            'images' => json_encode($uploadedImages),
            'status' => isset($body['status']) ? 1 : 0,
            'featured' => isset($body['featured']) ? 1 : 0,
        ]);

        $product->save();
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/products');
    }

    public function productEdit($id) {
        $product = Product::find($id);
        if (!$product) {
            $GLOBALS['router']->send404();
        }
        
        $categories = Category::all();
        $this->response->render('admin/products/edit', [
            'product' => $product,
            'categories' => $categories,
            'title' => 'Ürün Düzenle - Yönetim Paneli'
        ]);
    }

    public function productUpdate($id) {
        $product = Product::find($id);
        if (!$product) {
            $GLOBALS['router']->send404();
        }

        $body = $this->request->getBody();
        $categoriesChecked = isset($_POST['categories']) ? $_POST['categories'] : [];

        $product->name = isset($body['name']) ? $body['name'] : '';
        $product->model = isset($body['model']) ? $body['model'] : '';
        $product->brand_slug = isset($body['brand_slug']) ? $body['brand_slug'] : '';
        $product->price = (float)(isset($body['price']) ? $body['price'] : 0.0);
        $product->currency = isset($body['currency']) ? $body['currency'] : 'TRY';
        $product->stock = (int)(isset($body['stock']) ? $body['stock'] : 10);
        $product->description = isset($_POST['description']) ? $_POST['description'] : '';
        $product->categories = json_encode($categoriesChecked);
        $product->status = isset($body['status']) ? 1 : 0;
        $product->featured = isset($body['featured']) ? 1 : 0;

        if (!empty($body['slug'])) {
            $product->slug = $this->slugify($body['slug']);
        } else {
            $product->slug = $this->slugify($product->name);
        }

        $currentImages = $product->getImages();
        
        // Remove deleted images
        if (!empty($_POST['delete_images']) && is_array($_POST['delete_images'])) {
            foreach ($_POST['delete_images'] as $delImg) {
                if (($key = array_search($delImg, $currentImages)) !== false) {
                    unset($currentImages[$key]);
                    // Optionally delete the physical file here
                    $physicalPath = __DIR__ . '/../../public' . $delImg;
                    if (file_exists($physicalPath)) {
                        @unlink($physicalPath);
                    }
                }
            }
            $currentImages = array_values($currentImages); // reindex
        }

        $imageService = new ImageService('products');
        $uploadedFilesAssoc = [];
        if (!empty($_FILES['images'])) {
            $uploadedFilesAssoc = $imageService->uploadMultiple($_FILES['images']);
            $currentImages = array_merge($currentImages, array_values($uploadedFilesAssoc));
        }
        if (!empty($_POST['image_urls'])) {
            $currentImages = array_merge($currentImages, $imageService->fetchFromUrls($_POST['image_urls']));
        }

        $mainImage = isset($_POST['main_image']) ? $_POST['main_image'] : null;
        if ($mainImage) {
            $mainImagePath = null;
            if (strpos($mainImage, 'new::') === 0) {
                $filename = substr($mainImage, 5);
                if (isset($uploadedFilesAssoc[$filename])) {
                    $mainImagePath = $uploadedFilesAssoc[$filename];
                }
            } elseif (strpos($mainImage, 'existing::') === 0) {
                $mainImagePath = substr($mainImage, 10);
            }
            
            if ($mainImagePath && ($key = array_search($mainImagePath, $currentImages)) !== false) {
                unset($currentImages[$key]);
                array_unshift($currentImages, $mainImagePath);
                $currentImages = array_values($currentImages);
            }
        }

        $product->images = json_encode($currentImages);
        $product->image = ''; // Clear legacy image field since we migrated

        $product->save();
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/products');
    }

    public function productDelete($id) {
        $product = Product::find($id);
        if ($product) {
            $product->delete();
        }
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/products');
    }

    // Categories CRUD
    public function categories() {
        $categories = Category::all();

        // Search filter
        $search = trim($_GET['search'] ?? '');
        if ($search !== '') {
            $searchLower = mb_strtolower($search, 'UTF-8');
            $categories = array_values(array_filter($categories, function($c) use ($searchLower) {
                $name = mb_strtolower($c->name ?? '', 'UTF-8');
                $slug = mb_strtolower($c->slug ?? '', 'UTF-8');
                return strpos($name, $searchLower) !== false || strpos($slug, $searchLower) !== false;
            }));
        }

        // Sorting
        $sort = $_GET['sort'] ?? '';
        $order = $_GET['order'] ?? 'asc';
        $allowedSort = ['name', 'slug'];

        if ($sort !== '' && in_array($sort, $allowedSort)) {
            usort($categories, function($a, $b) use ($sort, $order) {
                $va = mb_strtolower((string)($a->$sort ?? ''), 'UTF-8');
                $vb = mb_strtolower((string)($b->$sort ?? ''), 'UTF-8');
                return $order === 'asc' ? strcmp($va, $vb) : strcmp($vb, $va);
            });
        }

        $this->response->render('admin/categories/index', [
            'categories' => $categories,
            'search' => $search,
            'sort' => $sort,
            'order' => $order,
            'title' => 'Kategori Yönetimi - Yönetim Paneli'
        ]);
    }

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

    public function categoryStore() {
        $body = $this->request->getBody();
        
        $name = isset($body['name']) ? $body['name'] : '';
        $slug = !empty($body['slug']) ? $this->slugify($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($GLOBALS['router']->getBaseUrl() . '/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]);
    }

    public function categoryEdit($id) {
        $category = Category::find($id);
        if (!$category) {
            $GLOBALS['router']->send404();
        }
        
        $categories = Category::all();
        $this->response->render('admin/categories/edit', [
            'category' => $category,
            'categories' => $categories,
            'title' => 'Kategori Düzenle - Yönetim Paneli'
        ]);
    }

    public function categoryUpdate($id) {
        $category = Category::find($id);
        if (!$category) {
            $GLOBALS['router']->send404();
        }

        $body = $this->request->getBody();

        $category->name = isset($body['name']) ? $body['name'] : '';
        
        if (!empty($body['slug'])) {
            $category->slug = $this->slugify($body['slug']);
        } else {
            $category->slug = $this->slugify($category->name);
        }

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

        $category->save();
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/categories');
    }

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

    // Settings Panel
    public function settings() {
        $settings = Settings::all();
        $this->response->render('admin/settings', [
            'settings' => $settings,
            'title' => 'Mağaza Ayarları - Yönetim Paneli'
        ]);
    }

    public function settingsUpdate() {
        $body = $this->request->getBody();
        
        $paymentMethods = isset($_POST['payment_methods']) && is_array($_POST['payment_methods']) ? $_POST['payment_methods'] : [];
        if (isset($paymentMethods['bank_transfer']['accounts']) && is_array($paymentMethods['bank_transfer']['accounts'])) {
            $paymentMethods['bank_transfer']['accounts'] = array_values($paymentMethods['bank_transfer']['accounts']);
        }

        Settings::updateAll([
            'store_name' => isset($body['store_name']) ? $body['store_name'] : '',
            'store_title' => isset($body['store_title']) ? $body['store_title'] : '',
            'store_description' => isset($body['store_description']) ? $body['store_description'] : '',
            'email' => isset($body['email']) ? $body['email'] : '',
            'telephone' => isset($body['telephone']) ? $body['telephone'] : '',
            'address' => isset($body['address']) ? $body['address'] : '',
            'google_client_id' => isset($body['google_client_id']) ? $body['google_client_id'] : '',
            'google_client_secret' => isset($body['google_client_secret']) ? $body['google_client_secret'] : '',
            'iyzico_api_key' => isset($body['iyzico_api_key']) ? $body['iyzico_api_key'] : '',
            'iyzico_secret_key' => isset($body['iyzico_secret_key']) ? $body['iyzico_secret_key'] : '',
            'iyzico_mode' => isset($body['iyzico_mode']) ? $body['iyzico_mode'] : 'sandbox',
            'shipping_methods' => isset($_POST['shipping_methods']) && is_array($_POST['shipping_methods']) ? array_values($_POST['shipping_methods']) : [],
            'payment_methods' => $paymentMethods,
            'meta_tags' => isset($_POST['meta_tags']) && is_array($_POST['meta_tags']) ? array_values($_POST['meta_tags']) : [],
            'head_scripts' => isset($_POST['head_scripts']) ? $_POST['head_scripts'] : '',
            'body_scripts' => isset($_POST['body_scripts']) ? $_POST['body_scripts'] : ''
        ]);
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/settings');
    }

    // Orders Panel
    public function orders() {
        $orders = Order::all();

        // Search filter
        $search = trim($_GET['search'] ?? '');
        if ($search !== '') {
            $searchLower = mb_strtolower($search, 'UTF-8');
            $orders = array_values(array_filter($orders, function($o) use ($searchLower) {
                $id = mb_strtolower((string)($o->id ?? ''), 'UTF-8');
                $name = mb_strtolower($o->customer_name ?? '', 'UTF-8');
                $phone = mb_strtolower($o->customer_phone ?? '', 'UTF-8');
                $email = mb_strtolower($o->customer_email ?? '', 'UTF-8');
                return strpos($id, $searchLower) !== false
                    || strpos($name, $searchLower) !== false
                    || strpos($phone, $searchLower) !== false
                    || strpos($email, $searchLower) !== false;
            }));
        }

        // Sorting
        $sort = $_GET['sort'] ?? '';
        $order = $_GET['order'] ?? 'desc';
        $allowedSort = ['id', 'customer_name', 'total', 'created_at', 'status'];

        if ($sort === '' || !in_array($sort, $allowedSort)) {
            $orders = array_reverse($orders);
        } else {
            usort($orders, function($a, $b) use ($sort, $order) {
                $va = $a->$sort ?? '';
                $vb = $b->$sort ?? '';
                if ($sort === 'total') {
                    return $order === 'asc' ? ($va <=> $vb) : ($vb <=> $va);
                }
                $va = mb_strtolower((string)$va, 'UTF-8');
                $vb = mb_strtolower((string)$vb, 'UTF-8');
                return $order === 'asc' ? strcmp($va, $vb) : strcmp($vb, $va);
            });
        }

        $this->response->render('admin/orders/index', [
            'orders' => $orders,
            'search' => $search,
            'sort' => $sort,
            'order' => $order,
            'title' => 'Siparişler - Yönetim Paneli'
        ]);
    }

    public function orderUpdateStatus($id) {
        $body = $this->request->getBody();
        $status = isset($body['status']) ? $body['status'] : 'pending';

        $order = Order::find($id);
        if ($order) {
            $order->status = $status;
            $order->save();
        }
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/orders');
    }

    public function orderEdit($id) {
        $order = Order::find($id);
        if (!$order) {
            $GLOBALS['router']->send404();
        }
        $this->response->render('admin/orders/edit', [
            'order' => $order,
            'title' => 'Sipariş Detayı - Yönetim Paneli'
        ]);
    }

    public function orderUpdate($id) {
        $order = Order::find($id);
        if ($order) {
            $body = $this->request->getBody();
            $order->status = isset($body['status']) ? $body['status'] : $order->status;
            
            // Shipping details
            $order->shipping_company = isset($body['shipping_company']) ? trim($body['shipping_company']) : ($order->shipping_company ?? '');
            $order->tracking_number = isset($body['tracking_number']) ? trim($body['tracking_number']) : ($order->tracking_number ?? '');
            
            $order->save();
        }
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/orders/edit/' . $id);
    }

    public function orderDelete($id) {
        $order = Order::find($id);
        if ($order) {
            $order->delete();
        }
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/orders');
    }

    // --- USERS MANAGEMENT ---
    public function users() {
        $users = User::all();

        // Search filter
        $search = trim($_GET['search'] ?? '');
        if ($search !== '') {
            $searchLower = mb_strtolower($search, 'UTF-8');
            $users = array_values(array_filter($users, function($u) use ($searchLower) {
                $name = mb_strtolower($u->name ?? '', 'UTF-8');
                $email = mb_strtolower($u->email ?? '', 'UTF-8');
                return strpos($name, $searchLower) !== false || strpos($email, $searchLower) !== false;
            }));
        }

        // Sorting
        $sort = $_GET['sort'] ?? '';
        $order = $_GET['order'] ?? 'asc';
        $allowedSort = ['name', 'email', 'role', 'created_at'];

        if ($sort !== '' && in_array($sort, $allowedSort)) {
            usort($users, function($a, $b) use ($sort, $order) {
                $va = mb_strtolower((string)($a->$sort ?? ''), 'UTF-8');
                $vb = mb_strtolower((string)($b->$sort ?? ''), 'UTF-8');
                return $order === 'asc' ? strcmp($va, $vb) : strcmp($vb, $va);
            });
        }

        $this->response->render('admin/users/index', [
            'users' => $users,
            'search' => $search,
            'sort' => $sort,
            'order' => $order,
            'title' => 'Kullanıcılar - Yönetim Paneli'
        ]);
    }

    public function userUpdateRole($id) {
        $user = User::find($id);
        if ($user) {
            $body = $this->request->getBody();
            $currentUser = $this->session->get('admin_user');
            if ($currentUser['id'] !== $user->id) {
                $role = isset($body['role']) ? $body['role'] : 'user';
                $allowed = ['admin', 'user', 'restricted'];
                $user->role = in_array($role, $allowed) ? $role : 'user';
                $user->save();
            }
        }
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/users');
    }

    public function userToggleStatus($id) {
        $user = User::find($id);
        if ($user) {
            $currentUser = $this->session->get('admin_user');
            if ($currentUser['id'] !== $user->id) {
                // Merge status into role: blocked users become 'restricted'
                $user->role = ((int)$user->status === 1) ? 'restricted' : 'user';
                $user->status = 1;
                $user->save();
            }
        }
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/users');
    }

    // --- THEME SETTINGS ---
    public function theme() {
        $settings = Settings::all();
        $this->response->render('admin/theme', [
            'settings' => $settings,
            'title' => 'Tema ve İçerik Yönetimi - Yönetim Paneli'
        ]);
    }

    public function themeUpdate() {
        $body = $_POST; // Use raw POST to prevent FILTER_SANITIZE_SPECIAL_CHARS from destroying JSON quotes and URLs
        
        $hero_sliders = isset($body['hero_sliders']) ? array_filter(array_map('trim', explode("\n", $body['hero_sliders']))) : [];
        $header_top_bar = isset($body['header_top_bar']) ? trim($body['header_top_bar']) : '';
        
        $processJson = function($key) use ($body) {
            if (isset($body[$key])) {
                $rawJson = trim($body[$key]);
                // In case it was somehow sanitized, decode it (though $_POST should be raw)
                $decoded = json_decode($rawJson, true);
                if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
                    return $decoded;
                }
            }
            return Settings::get($key, []);
        };

        Settings::updateAll([
            'hero_sliders' => $hero_sliders,
            'features_bar' => $processJson('features_bar'),
            'social_links' => $processJson('social_links'),
            'footer_partners' => $processJson('footer_partners'),
            'footer_quick_links' => $processJson('footer_quick_links'),
            'header_top_bar' => $header_top_bar
        ]);
        
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/theme');
    }

    // --- STATIC PAGES MANAGEMENT ---
    public function pages() {
        $pages = Page::all();
        $this->response->render('admin/pages/index', [
            'pages' => $pages,
            'title' => 'Sabit Sayfalar - Yönetim Paneli'
        ]);
    }

    public function pageCreate() {
        $this->response->render('admin/pages/create', [
            'title' => 'Yeni Sayfa Ekle - Yönetim Paneli'
        ]);
    }

    public function pageStore() {
        $body = $this->request->getBody();
        $page = new Page([
            'title' => isset($body['title']) ? $body['title'] : '',
            'slug' => $this->slugify(isset($body['title']) ? $body['title'] : ''),
            'content' => isset($_POST['content']) ? $_POST['content'] : ''
        ]);
        $page->save();
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/pages');
    }

    public function pageEdit($id) {
        $page = Page::find($id);
        if (!$page) $GLOBALS['router']->send404();
        
        $this->response->render('admin/pages/edit', [
            'page' => $page,
            'title' => 'Sayfa Düzenle - Yönetim Paneli'
        ]);
    }

    public function pageUpdate($id) {
        $page = Page::find($id);
        if (!$page) $GLOBALS['router']->send404();
        
        $body = $this->request->getBody();
        $page->title = isset($body['title']) ? $body['title'] : '';
        $page->slug = $this->slugify(isset($body['title']) ? $body['title'] : '');
        $page->content = isset($_POST['content']) ? $_POST['content'] : '';
        $page->save();
        
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/pages');
    }

    public function pageDelete($id) {
        $page = Page::find($id);
        if ($page) $page->delete();
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/pages');
    }

    public function brands() {
        $settings = Settings::all();
        $brands = isset($settings['brands']) ? $settings['brands'] : [];
        $this->response->render('admin/brands', [
            'brands' => $brands,
            'title' => 'Marka Yönetimi - Yönetim Paneli'
        ]);
    }

    private function uploadBrandImage(): string {
        if (empty($_FILES['brand_image']) || $_FILES['brand_image']['error'] !== UPLOAD_ERR_OK) {
            return '';
        }
        $imageService = new ImageService('brands');
        $uploaded = $imageService->uploadMultiple([
            'name'     => [$_FILES['brand_image']['name']],
            'type'     => [$_FILES['brand_image']['type']],
            'tmp_name' => [$_FILES['brand_image']['tmp_name']],
            'error'    => [$_FILES['brand_image']['error']],
            'size'     => [$_FILES['brand_image']['size']],
        ]);
        if (!empty($uploaded)) {
            return reset($uploaded);
        }
        return '';
    }

    public function brandStore() {
        $body = $this->request->getBody();
        $name = isset($body['name']) ? trim($body['name']) : '';
        if ($name === '') {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/brands');
        }
        $slug = !empty($body['slug']) ? $this->slugify($body['slug']) : $this->slugify($name);
        
        $imagePath = $this->uploadBrandImage();

        $settings = Settings::all();
        $brands = isset($settings['brands']) ? $settings['brands'] : [];
        foreach ($brands as $b) {
            if ($b['slug'] === $slug) {
                $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/brands');
            }
        }
        $brandEntry = ['name' => $name, 'slug' => $slug];
        if ($imagePath) {
            $brandEntry['image'] = $imagePath;
        }
        $brands[] = $brandEntry;
        Settings::set('brands', $brands);
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/brands');
    }

    public function brandUpdate($id) {
        $body = $this->request->getBody();
        $name = isset($body['name']) ? trim($body['name']) : '';
        if ($name === '') {
            $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/brands');
        }
        $slug = !empty($body['slug']) ? $this->slugify($body['slug']) : $this->slugify($name);
        
        $settings = Settings::all();
        $brands = isset($settings['brands']) ? $settings['brands'] : [];
        if (isset($brands[$id])) {
            $entry = ['name' => $name, 'slug' => $slug];
            $uploaded = $this->uploadBrandImage();
            if ($uploaded) {
                $entry['image'] = $uploaded;
            } else {
                $entry['image'] = $brands[$id]['image'] ?? '';
            }
            $brands[$id] = $entry;
        }
        Settings::set('brands', $brands);
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/brands');
    }

    public function brandDelete($slug) {
        $settings = Settings::all();
        $brands = isset($settings['brands']) ? $settings['brands'] : [];
        $brands = array_values(array_filter($brands, function($b) use ($slug) {
            return $b['slug'] !== $slug;
        }));
        Settings::set('brands', array_values($brands));
        $this->response->redirect($GLOBALS['router']->getBaseUrl() . '/admin/brands');
    }

    // Helper method to slugify text (handles Turkish chars)
    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('/[^a-zA-Z0-9\s\-_]/', '', $text);
        $text = preg_replace('/[\s\-]+/', '-', $text);
        $text = strtolower(trim($text, '-'));
        return $text;
    }

    public function database() {
        $this->response->render('admin/database', [
            'title' => 'Veritabanı Yönetimi',
        ]);
    }
}
