<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Coupon;
use App\Models\Promotion;
use App\Models\Service;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Illuminate\View\View;

class PromotionController extends Controller
{
    public function index(): View
    {
        return view('tenant.promotions.index', [
            'promotions' => Promotion::latest()->paginate(10),
            'coupons' => Coupon::where('scope', 'company')->latest()->paginate(10, ['*'], 'coupons_page'),
            'services' => Service::active()->orderBy('name')->get(),
        ]);
    }

    public function storePromotion(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'description' => ['nullable', 'string'],
            'discount_type' => ['required', 'in:percentage,fixed'],
            'discount_value' => ['required', 'numeric', 'min:0'],
            'applies_to_all_services' => ['nullable', 'boolean'],
            'service_ids' => ['nullable', 'array'],
            'service_ids.*' => ['integer', 'exists:services,id'],
            'starts_at' => ['nullable', 'date'],
            'ends_at' => ['nullable', 'date', 'after_or_equal:starts_at'],
            'usage_limit' => ['nullable', 'integer', 'min:1'],
            'is_active' => ['nullable', 'boolean'],
            'is_featured' => ['nullable', 'boolean'],
        ]);

        $appliesToAll = $request->boolean('applies_to_all_services');

        if (! $appliesToAll && blank($data['service_ids'] ?? null)) {
            return back()
                ->withErrors(['service_ids' => 'Selecciona al menos un servicio o marca todos los servicios.'])
                ->withInput();
        }

        Promotion::create($data + [
            'slug' => Str::slug($data['name']).'-'.Str::lower(Str::random(5)),
            'applies_to_all_services' => $appliesToAll,
            'service_ids' => $appliesToAll ? null : array_map('intval', $data['service_ids'] ?? []),
            'is_active' => $request->boolean('is_active', true),
            'is_featured' => $request->boolean('is_featured'),
        ]);

        return back()->with('success', 'Promoción creada.');
    }

    public function storeCoupon(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'code' => ['required', 'string', 'max:50'],
            'discount_type' => ['required', 'in:percentage,fixed'],
            'discount_value' => ['required', 'numeric', 'min:0'],
            'min_amount' => ['nullable', 'numeric', 'min:0'],
            'max_discount' => ['nullable', 'numeric', 'min:0'],
            'starts_at' => ['nullable', 'date'],
            'ends_at' => ['nullable', 'date', 'after_or_equal:starts_at'],
            'usage_limit' => ['nullable', 'integer', 'min:1'],
            'usage_limit_per_customer' => ['nullable', 'integer', 'min:1'],
            'is_active' => ['nullable', 'boolean'],
        ]);

        Coupon::create(array_merge($data, [
            'code' => Str::upper($data['code']),
            'scope' => 'company',
            'is_active' => $request->boolean('is_active', true),
        ]));

        return back()->with('success', 'Cupón creado.');
    }

    public function togglePromotion(Promotion $promotion): RedirectResponse
    {
        $promotion->update(['is_active' => ! $promotion->is_active]);

        return back()->with('success', 'Estado de la promoción actualizado.');
    }

    public function toggleCoupon(Coupon $coupon): RedirectResponse
    {
        $coupon->update(['is_active' => ! $coupon->is_active]);

        return back()->with('success', 'Estado del cupón actualizado.');
    }
}
