<?php

namespace App\Http\Controllers;

use App\Models\HeaderFooterSetting;
use App\Models\MenuItem;
use App\Models\Category;
use App\Models\Product;
use App\Models\Page;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class HeaderFooterController extends Controller
{
    /**
     * Get public header/footer settings
     */
    public function getPublic()
    {
        $settings = HeaderFooterSetting::first();
        
        if (!$settings) {
            $settings = HeaderFooterSetting::create([]);
        }

        $headerMenus = MenuItem::where('location', 'header')
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        $footerMenus = MenuItem::where('location', 'footer')
            ->where('is_active', true)
            ->orderBy('sort_order')
            ->get();

        return response()->json([
            'data' => [
                'settings' => $settings,
                'header_menus' => $headerMenus,
                'footer_menus' => $footerMenus,
            ]
        ]);
    }

    /**
     * Get all settings (admin)
     */
    public function getSettings()
    {
        $settings = HeaderFooterSetting::first();
        
        if (!$settings) {
            $settings = HeaderFooterSetting::create([]);
        }

        return response()->json(['data' => $settings]);
    }

    /**
     * Update settings
     */
    public function updateSettings(Request $request)
    {
        $validated = $request->validate([
            'header_bg_color' => 'nullable|string|max:20',
            'header_text_color' => 'nullable|string|max:20',
            'header_link_color' => 'nullable|string|max:20',
            'header_link_hover_color' => 'nullable|string|max:20',
            'logo_text' => 'nullable|string|max:100',
            'footer_bg_color' => 'nullable|string|max:20',
            'footer_text_color' => 'nullable|string|max:20',
            'footer_heading_color' => 'nullable|string|max:20',
            'footer_link_color' => 'nullable|string|max:20',
            'footer_link_hover_color' => 'nullable|string|max:20',
            'footer_description' => 'nullable|string',
            'footer_copyright' => 'nullable|string',
            'phone' => 'nullable|string|max:50',
            'email' => 'nullable|email|max:100',
            'address' => 'nullable|string',
            'social_instagram' => 'nullable|url|max:255',
            'social_telegram' => 'nullable|url|max:255',
            'social_whatsapp' => 'nullable|string|max:255',
        ]);

        $settings = HeaderFooterSetting::first();
        
        if (!$settings) {
            $settings = HeaderFooterSetting::create($validated);
        } else {
            $settings->update($validated);
        }

        return response()->json([
            'message' => 'تنظیمات با موفقیت ذخیره شد',
            'data' => $settings
        ]);
    }

    /**
     * Upload logo
     */
    public function uploadLogo(Request $request)
    {
        $request->validate([
            'logo' => 'required|image|mimes:jpeg,png,jpg,svg,webp|max:512000',
        ]);

        $settings = HeaderFooterSetting::first();
        if (!$settings) {
            $settings = HeaderFooterSetting::create([]);
        }

        // Delete old logo
        if ($settings->logo_image) {
            Storage::disk('public')->delete($settings->logo_image);
        }

        // Store new logo
        $path = $request->file('logo')->store('logos', 'public');
        $settings->update(['logo_image' => $path]);

        return response()->json([
            'message' => 'لوگو با موفقیت آپلود شد',
            'data' => $settings
        ]);
    }

    /**
     * Get all menu items
     */
    public function getMenuItems(Request $request)
    {
        $location = $request->query('location');
        
        $query = MenuItem::orderBy('location')->orderBy('sort_order');
        
        if ($location) {
            $query->where('location', $location);
        }

        $items = $query->get();

        return response()->json(['data' => $items]);
    }

    /**
     * Create menu item
     */
    public function createMenuItem(Request $request)
    {
        $validated = $request->validate([
            'location' => 'required|in:header,footer',
            'title' => 'required|string|max:100',
            'link' => 'required|string|max:255',
            'icon' => 'nullable|string|max:50',
            'icon_type' => 'nullable|in:emoji,image',
            'icon_image' => 'nullable|image|mimes:jpeg,png,jpg,svg,webp|max:51200',
            'sort_order' => 'nullable|integer',
            'is_active' => 'nullable|boolean',
            'open_in_new_tab' => 'nullable|boolean',
            'group' => 'nullable|string|max:50',
        ]);

        // Handle image upload if icon_type is image
        if ($request->icon_type === 'image' && $request->hasFile('icon_image')) {
            $validated['icon_image'] = $request->file('icon_image')->store('icons/menus', 'public');
        }

        $item = MenuItem::create($validated);

        return response()->json([
            'message' => 'منو با موفقیت ایجاد شد',
            'data' => $item
        ], 201);
    }

    /**
     * Update menu item
     */
    public function updateMenuItem(Request $request, $id)
    {
        $item = MenuItem::findOrFail($id);

        $rules = [
            'location' => 'required|in:header,footer',
            'title' => 'required|string|max:100',
            'link' => 'required|string|max:255',
            'icon' => 'nullable|string|max:50',
            'icon_type' => 'nullable|in:emoji,image',
            'sort_order' => 'nullable|integer',
            'is_active' => 'nullable|boolean',
            'open_in_new_tab' => 'nullable|boolean',
            'group' => 'nullable|string|max:50',
        ];

        // Only validate icon_image if it's actually being uploaded
        if ($request->hasFile('icon_image')) {
            $rules['icon_image'] = 'nullable|image|mimes:jpeg,png,jpg,svg,webp|max:51200';
        }

        $validated = $request->validate($rules);

        // Handle image upload if icon_type is image
        if ($request->icon_type === 'image' && $request->hasFile('icon_image')) {
            // Delete old image
            if ($item->icon_image) {
                Storage::disk('public')->delete($item->icon_image);
            }
            $validated['icon_image'] = $request->file('icon_image')->store('icons/menus', 'public');
        } elseif ($request->icon_type === 'emoji') {
            // If switching to emoji, clear icon_image
            if ($item->icon_image) {
                Storage::disk('public')->delete($item->icon_image);
            }
            $validated['icon_image'] = null;
        }

        $item->update($validated);

        return response()->json([
            'message' => 'منو با موفقیت بروزرسانی شد',
            'data' => $item
        ]);
    }

    /**
     * Delete menu item
     */
    public function deleteMenuItem($id)
    {
        $item = MenuItem::findOrFail($id);
        
        // Delete associated image
        if ($item->icon_image) {
            Storage::disk('public')->delete($item->icon_image);
        }
        
        $item->delete();

        return response()->json(['message' => 'منو با موفقیت حذف شد']);
    }

    /**
     * Get available pages for linking (used in dropdowns)
     */
    public function getAvailablePages()
    {
        $categories = Category::all(['id', 'name']);
        $products = Product::all(['id', 'name']);
        $pages = Page::where('is_published', true)->get(['id', 'slug', 'title']);

        $allPages = [
            ['type' => 'header', 'label' => '📄 صفحات اصلی'],
            ['value' => '/', 'label' => '🏠 صفحه اصلی'],
            ['value' => '/products', 'label' => '🛍️ محصولات'],
            ['value' => '/pages', 'label' => '📄 لیست صفحات'],
            ['value' => '/cart', 'label' => '🛒 سبد خرید'],
            ['value' => '/orders', 'label' => '📋 سفارشات من'],
            ['value' => '/register', 'label' => '✨ ثبت‌نام'],
            ['value' => '/login', 'label' => '🔐 ورود'],
        ];

        if ($pages->count() > 0) {
            $allPages[] = ['type' => 'header', 'label' => '📑 صفحات کاستوم'];
            foreach ($pages as $page) {
                $allPages[] = ['value' => "/pages/{$page->slug}", 'label' => "   {$page->title}"];
            }
        }

        if ($categories->count() > 0) {
            $allPages[] = ['type' => 'header', 'label' => '🗂️ دسته‌بندی‌ها'];
            foreach ($categories as $cat) {
                $allPages[] = ['value' => "/categories/{$cat->id}", 'label' => "   {$cat->name}"];
            }
        }

        if ($products->count() > 0) {
            $allPages[] = ['type' => 'header', 'label' => '📦 محصولات'];
            foreach ($products as $prod) {
                $allPages[] = ['value' => "/products/{$prod->id}", 'label' => "   {$prod->name}"];
            }
        }

        return response()->json(['data' => $allPages]);
    }
}
