<?php

namespace App\Http\Controllers;

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

class AdminVoucherController extends Controller
{
    public function index()
    {
        return view('admin.vouchers.index', [
            'vouchers' => Voucher::latest()->paginate(20),
        ]);
    }

    public function create()
    {
        return view('admin.vouchers.form', ['voucher' => new Voucher]);
    }

    public function store(Request $request, AuditLogService $audit)
    {
        $voucher = Voucher::create($this->payload($request));
        $audit->record('admin.voucher_created', $voucher, ['code' => $voucher->code]);

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

    public function edit(Voucher $voucher)
    {
        return view('admin.vouchers.form', compact('voucher'));
    }

    public function update(Request $request, Voucher $voucher, AuditLogService $audit)
    {
        $voucher->update($this->payload($request, $voucher));
        $audit->record('admin.voucher_updated', $voucher, ['code' => $voucher->code]);

        return redirect()->route('admin.vouchers.index')->with('status', 'تم تحديث كود الشحن.');
    }

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

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

    private function payload(Request $request, ?Voucher $voucher = null): array
    {
        $data = $request->validate([
            'code' => ['required', 'string', 'max:64', Rule::unique('vouchers', 'code')->ignore($voucher)],
            'name_ar' => ['required', 'string', 'max:160'],
            'name_en' => ['nullable', 'string', 'max:160'],
            'amount_minor' => ['required', 'integer', 'min:1'],
            '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_user' => ['nullable', 'boolean'],
        ]);

        $data['code'] = strtoupper(trim($data['code']));
        $data['currency_code'] = 'EGP';
        $data['is_active'] = $request->boolean('is_active');
        $data['once_per_user'] = $request->boolean('once_per_user');

        return $data;
    }
}
