<?php

namespace App\Http\Controllers;

use App\Models\Coupon;
use App\Services\AuditLogService;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class AdminCouponController extends Controller
{
    public function index(Request $request)
    {
        $query = trim((string) $request->query('q', ''));

        return view('admin.coupons.index', [
            'coupons' => Coupon::query()
                ->withCount('redemptions')
                ->when($query !== '', fn ($builder) => $builder
                    ->where('code', 'like', "%{$query}%")
                    ->orWhere('name_ar', 'like', "%{$query}%"))
                ->latest()
                ->paginate(20)
                ->withQueryString(),
            'query' => $query,
        ]);
    }

    public function create()
    {
        return view('admin.coupons.form', [
            'coupon' => new Coupon([
                'type' => 'fixed',
                'is_active' => true,
                'once_per_customer' => true,
                'min_subtotal_minor' => 0,
                'value_minor' => 0,
                'percent_off' => 0,
            ]),
        ]);
    }

    public function store(Request $request, AuditLogService $audit)
    {
        $coupon = Coupon::create($this->validatedData($request));
        $audit->record('admin.coupon_created', $coupon, ['code' => $coupon->code]);

        return redirect()->route('admin.coupons.index')->with('status', 'تم إنشاء الكوبون.');
    }

    public function edit(Coupon $coupon)
    {
        return view('admin.coupons.form', ['coupon' => $coupon]);
    }

    public function update(Request $request, Coupon $coupon, AuditLogService $audit)
    {
        $coupon->update($this->validatedData($request, $coupon));
        $audit->record('admin.coupon_updated', $coupon, ['code' => $coupon->code]);

        return back()->with('status', 'تم تحديث الكوبون.');
    }

    public function destroy(Coupon $coupon, AuditLogService $audit)
    {
        $coupon->update(['is_active' => false]);
        $audit->record('admin.coupon_disabled', $coupon, ['code' => $coupon->code]);

        return back()->with('status', 'تم تعطيل الكوبون بأمان.');
    }

    private function validatedData(Request $request, ?Coupon $coupon = null): array
    {
        $data = $request->validate([
            'code' => ['required', 'string', 'max:40', Rule::unique('coupons', 'code')->ignore($coupon)],
            'name_ar' => ['required', 'string', 'max:140'],
            'name_en' => ['nullable', 'string', 'max:140'],
            'type' => ['required', 'in:fixed,percent'],
            'value_minor' => ['nullable', 'integer', 'min:0'],
            'percent_off' => ['nullable', 'integer', 'min:0', 'max:100'],
            'max_discount_minor' => ['nullable', 'integer', 'min:0'],
            'min_subtotal_minor' => ['nullable', 'integer', 'min:0'],
            'usage_limit' => ['nullable', 'integer', 'min:1'],
            'starts_at' => ['nullable', 'date'],
            'ends_at' => ['nullable', 'date', 'after_or_equal:starts_at'],
            'is_active' => ['nullable', 'boolean'],
            'once_per_customer' => ['nullable', 'boolean'],
        ]);

        $data['code'] = strtoupper(trim($data['code']));
        $data['value_minor'] = (int) ($data['value_minor'] ?? 0);
        $data['percent_off'] = (int) ($data['percent_off'] ?? 0);
        $data['min_subtotal_minor'] = (int) ($data['min_subtotal_minor'] ?? 0);
        $data['is_active'] = $request->boolean('is_active');
        $data['once_per_customer'] = $request->boolean('once_per_customer');

        return $data;
    }
}
