<?php

namespace App\Http\Controllers\Admin\TopUp;

use App\Http\Controllers\Controller;
use App\Models\PwPromo;
use App\Models\PwPromoUsage;
use Illuminate\Http\Request;
use Inertia\Inertia;

class PromoController extends Controller
{
    public function index()
    {
        $promos = PwPromo::orderBy('created_at', 'desc')->get();

        return Inertia::render('admin/topup/promo/index', [
            'promos' => $promos,
        ]);
    }

    public function create()
    {
        return Inertia::render('admin/topup/promo/create');
    }

    public function edit($id)
    {
        $promo = PwPromo::findOrFail($id);

        return Inertia::render('admin/topup/promo/edit', [
            'promo' => $promo,
        ]);
    }

    public function store(Request $request)
    {
        $isAuto = filter_var($request->is_auto, FILTER_VALIDATE_BOOLEAN);

        $rules = [
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:500',
            'discount_type' => 'required|in:percentage,fixed,bonus_gold_fixed,bonus_gold_percentage',
            'discount_value' => 'required|numeric|min:0',
            'min_amount' => 'required|integer|min:0',
            'max_discount' => 'nullable|integer|min:0',
            'usage_limit' => 'nullable|integer|min:1',
            'per_user_limit' => 'required|integer|min:1',
            'is_active' => 'nullable',
            'is_auto' => 'nullable',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
        ];

        // Only require code if not auto promo
        if (! $isAuto) {
            $rules['code'] = 'required|string|max:50|unique:pw_promo,code';
        }

        $request->validate($rules);

        $isActive = filter_var($request->is_active, FILTER_VALIDATE_BOOLEAN);
        $code = $isAuto
            ? 'AUTO_'.str_replace('.', '', $request->discount_value).'_'.$request->min_amount.'_'.time()
            : strtoupper($request->code);
        $discountType = $isAuto ? 'bonus_gold_percentage' : $request->discount_type;

        PwPromo::create([
            'code' => $code,
            'name' => $request->name,
            'description' => $request->description ?: null,
            'discount_type' => $discountType,
            'discount_value' => $request->discount_value,
            'min_amount' => $request->min_amount,
            'max_discount' => $request->max_discount !== '' && $request->max_discount !== null ? $request->max_discount : null,
            'usage_limit' => $request->usage_limit !== '' && $request->usage_limit !== null ? $request->usage_limit : null,
            'per_user_limit' => $request->per_user_limit,
            'is_active' => $isActive,
            'is_auto' => $isAuto,
            'start_date' => $request->start_date ?: null,
            'end_date' => $request->end_date ?: null,
        ]);

        return redirect()->route('admin.topup.promo.index')->with('success', 'Promo code created successfully.');
    }

    public function update(Request $request, $id)
    {
        $promo = PwPromo::findOrFail($id);

        $isAuto = filter_var($request->is_auto, FILTER_VALIDATE_BOOLEAN);

        $rules = [
            'name' => 'required|string|max:100',
            'description' => 'nullable|string|max:500',
            'discount_type' => 'required|in:percentage,fixed,bonus_gold_fixed,bonus_gold_percentage',
            'discount_value' => 'required|numeric|min:0',
            'min_amount' => 'required|integer|min:0',
            'max_discount' => 'nullable|integer|min:0',
            'usage_limit' => 'nullable|integer|min:1',
            'per_user_limit' => 'required|integer|min:1',
            'is_active' => 'nullable',
            'is_auto' => 'nullable',
            'start_date' => 'nullable|date',
            'end_date' => 'nullable|date|after_or_equal:start_date',
        ];

        // Only require code if not auto promo
        if (! $isAuto) {
            $rules['code'] = 'required|string|max:50|unique:pw_promo,code,'.$id;
        }

        $request->validate($rules);

        $isActive = filter_var($request->is_active, FILTER_VALIDATE_BOOLEAN);
        $discountType = $isAuto ? 'bonus_gold_percentage' : $request->discount_type;

        $updateData = [
            'name' => $request->name,
            'description' => $request->description ?: null,
            'discount_type' => $discountType,
            'discount_value' => $request->discount_value,
            'min_amount' => $request->min_amount,
            'max_discount' => $request->max_discount !== '' && $request->max_discount !== null ? $request->max_discount : null,
            'usage_limit' => $request->usage_limit !== '' && $request->usage_limit !== null ? $request->usage_limit : null,
            'per_user_limit' => $request->per_user_limit,
            'is_active' => $isActive,
            'is_auto' => $isAuto,
            'start_date' => $request->start_date ?: null,
            'end_date' => $request->end_date ?: null,
        ];

        if (! $isAuto) {
            $updateData['code'] = strtoupper($request->code);
        }

        $promo->update($updateData);

        return back()->with('success', 'Promo code updated successfully.');
    }

    public function destroy($id)
    {
        $promo = PwPromo::findOrFail($id);
        $promo->delete();

        return back()->with('success', 'Promo code deleted successfully.');
    }

    public function toggleActive($id)
    {
        $promo = PwPromo::findOrFail($id);
        $promo->is_active = ! $promo->is_active;
        $promo->save();

        return back()->with('success', 'Promo code status updated.');
    }

    public function usageHistory($id)
    {
        $promo = PwPromo::findOrFail($id);
        $usages = PwPromoUsage::where('promo_id', $id)
            ->with('user:id,name,email')
            ->orderBy('created_at', 'desc')
            ->limit(100)
            ->get();

        return response()->json([
            'promo' => $promo,
            'usages' => $usages,
        ]);
    }
}
