<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class OrderCloseRequest extends FormRequest
{
    public function authorize(): bool
    {
        return true;
    }

    public function rules(): array
    {
        return [
            'tipe_pembayaran' => ['required', Rule::in(['cash', 'transfer', 'qris'])],
            'no_transaksi_pembayaran' => ['nullable', 'required_unless:tipe_pembayaran,cash', 'string', 'max:255'],
            'bank_account_id' => ['nullable', 'required_if:tipe_pembayaran,transfer', 'integer', 'exists:master_bank_accounts,id'],
            'bayar' => ['nullable', 'required_if:tipe_pembayaran,cash', 'numeric', 'min:0'],
            'discount_id' => ['nullable', 'integer', 'exists:master_discounts,id'],
        ];
    }

    public function withValidator($validator): void
    {
        $validator->after(function ($validator) {
            $tipe = (string) $this->input('tipe_pembayaran');
            $bayar = $this->input('bayar');
            $order = $this->route('order');

            if ($tipe === 'cash' && $order && $bayar !== null) {
                $grandTotal = (float) ($order->grand_total ?? 0);
                $discountId = $this->input('discount_id');
                $discountAmount = 0.0;
                if ($discountId) {
                    $discount = \App\Models\MasterDiscount::query()
                        ->where('id', $discountId)
                        ->where('is_active', true)
                        ->first();
                    if ($discount) {
                        if ($discount->tipe === 'percent') {
                            $discountAmount = round($grandTotal * ((float) $discount->nilai / 100), 2);
                        } else {
                            $discountAmount = min($grandTotal, (float) $discount->nilai);
                        }
                    }
                }
                $totalAfterDiscount = max(0, $grandTotal - $discountAmount);
                if ((float) $bayar < $totalAfterDiscount) {
                    $validator->errors()->add('bayar', 'Nominal bayar harus lebih besar atau sama dengan total.');
                }
            }
        });
    }
}
