<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ProductCategory;
use App\Models\Coupon;
use App\Models\Setting;
use App\Models\ShippingZone;
use Illuminate\Http\Request;
use Inertia\Inertia;

class StoreSettingsController extends Controller
{
    /**
     * Display the store settings page.
     */
    public function index()
    {
        return Inertia::render('Admin/Store/Settings/Index', [
            'categories' => ProductCategory::withCount('products')->orderBy('order')->get(),
            'coupons' => Coupon::withCount('usages')->orderBy('created_at', 'desc')->get(),
            'shippingSettings' => [
                'flat_rate' => Setting::get('store_shipping_flat_rate', '5.00'),
                'free_shipping_threshold' => Setting::get('store_free_shipping_threshold', '50.00'),
                'enable_free_shipping' => Setting::get('store_enable_free_shipping', 'true') === 'true',
                'shipping_countries' => Setting::get('store_shipping_countries', 'DO,US,ES'),
            ],
            'shippingZones' => ShippingZone::ordered()->get(),
            'taxSettings' => [
                'default_tax_rate' => Setting::get('store_default_tax_rate', '18'),
                'enable_tax' => Setting::get('store_enable_tax', 'true') === 'true',
                'tax_included' => Setting::get('store_tax_included', 'false') === 'true',
            ],
            'generalSettings' => [
                'store_name' => Setting::get('store_name', 'Tienda CoachPro'),
                'store_description' => Setting::get('store_description', ''),
                'store_email' => Setting::get('store_email', ''),
                'store_phone' => Setting::get('store_phone', ''),
                'store_currency' => Setting::get('store_currency', 'USD'),
                'enable_store' => Setting::get('store_enabled', 'true') === 'true',
            ],
        ]);
    }

    /**
     * Update shipping settings.
     */
    public function updateShipping(Request $request)
    {
        $validated = $request->validate([
            'flat_rate' => 'required|numeric|min:0',
            'free_shipping_threshold' => 'required|numeric|min:0',
            'enable_free_shipping' => 'boolean',
            'shipping_countries' => 'nullable|string',
        ]);

        Setting::set('store_shipping_flat_rate', $validated['flat_rate']);
        Setting::set('store_free_shipping_threshold', $validated['free_shipping_threshold']);
        Setting::set('store_enable_free_shipping', $validated['enable_free_shipping'] ? 'true' : 'false');
        Setting::set('store_shipping_countries', $validated['shipping_countries'] ?? '');

        return back()->with('success', 'Configuración de envío actualizada.');
    }

    /**
     * Update tax settings.
     */
    public function updateTax(Request $request)
    {
        $validated = $request->validate([
            'default_tax_rate' => 'required|numeric|min:0|max:100',
            'enable_tax' => 'boolean',
            'tax_included' => 'boolean',
        ]);

        Setting::set('store_default_tax_rate', $validated['default_tax_rate']);
        Setting::set('store_enable_tax', $validated['enable_tax'] ? 'true' : 'false');
        Setting::set('store_tax_included', $validated['tax_included'] ? 'true' : 'false');

        return back()->with('success', 'Configuración de impuestos actualizada.');
    }

    /**
     * Update general store settings.
     */
    public function updateGeneral(Request $request)
    {
        $validated = $request->validate([
            'store_name' => 'required|string|max:255',
            'store_description' => 'nullable|string|max:500',
            'store_email' => 'nullable|email',
            'store_phone' => 'nullable|string|max:20',
            'store_currency' => 'required|string|size:3',
            'enable_store' => 'boolean',
        ]);

        Setting::set('store_name', $validated['store_name']);
        Setting::set('store_description', $validated['store_description'] ?? '');
        Setting::set('store_email', $validated['store_email'] ?? '');
        Setting::set('store_phone', $validated['store_phone'] ?? '');
        Setting::set('store_currency', $validated['store_currency']);
        Setting::set('store_enabled', $validated['enable_store'] ? 'true' : 'false');

        return back()->with('success', 'Configuración general actualizada.');
    }

    /**
     * Add a new shipping zone.
     */
    public function addShippingZone(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'cost' => 'required|numeric|min:0',
            'delivery_time' => 'nullable|string|max:100',
            'is_active' => 'boolean',
        ]);

        $order = ShippingZone::max('order') + 1;
        ShippingZone::create(array_merge($validated, ['order' => $order]));

        return back()->with('success', 'Zona de envío agregada.');
    }

    /**
     * Update an existing shipping zone.
     */
    public function updateShippingZone(Request $request, ShippingZone $shippingZone)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'cost' => 'required|numeric|min:0',
            'delivery_time' => 'nullable|string|max:100',
            'is_active' => 'boolean',
        ]);

        $shippingZone->update($validated);

        return back()->with('success', 'Zona de envío actualizada.');
    }

    /**
     * Delete a shipping zone.
     */
    public function deleteShippingZone(ShippingZone $shippingZone)
    {
        $shippingZone->delete();

        return back()->with('success', 'Zona de envío eliminada.');
    }
}
