<?php


namespace App\Models\PaymentManagement\Traits;



use App\Models\PaymentManagement\Payment;
use App\Models\PaymentManagement\PaymentMethod;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\File;


trait HasPayments{

    public function payments(){
        return $this->morphMany(
            Payment::class,
            Payment::MORPH_FUNCTION_NAME,
            Payment::MORPH_TYPE_COLUMN,
            Payment::MORPH_ID_COLUMN
        );
    }


    public function addPayment($datas,$imageRequired = false){
        $payment_table = (new Payment)->getTable();
        $payment_method_table = (new PaymentMethod)->getTable();

        $rules = [
            'payment_method_id' => ['required',"exists:$payment_method_table,id"],
            'paid_at' => ['nullable',"date"],
            'paid_amount' => ["required","numeric","min:10"],
            'remaining_amount' => ["nullable","numeric","min:10"],
           // 'provider_reference' =>  ['required','min:2',"unique:$payment_table,provider_reference"],
            'provider_reference' =>  [
                Rule::unique($payment_table,"provider_reference")
                    ->when(isset($datas['payment_method_id']),fn ($q) =>$q->where('payment_method_id',$datas['payment_method_id']))

            ],
        ];

        if (isset($datas['reference_confirmation'])){
            $rules['provider_reference_confirmation'] = ["required"];
            $rules['provider_reference'][] = "same:reference_confirmation";
        }

        if ($imageRequired){
            $rules['image'] =  ['required', File::image()->max(2048)];
        }

        if (isset($datas['payment_method_id'])){
            $payment_method = PaymentMethod::find($datas['payment_method_id']);
            if (filled($payment_method) and $payment_method->code != PaymentMethod::CASH){
                $rules['provider_reference'][] = 'required';
                $rules['provider_reference'][] = 'min:2';
            }
        }

       // dd($rules);

        $result = [
            'success' =>false,
            'message' => "",
            'errors' =>  [],
        ];

        $validation = Validator::make(
                        $datas,
                        $rules,Payment::validations_messages(),
                        Payment::validations_attributes()
                    ); // (boolean)

        if ($validation->passes()){
            if (!isset($datas['paid_at'])){
                $datas['paid_at'] = now();
            }
            $payment =  $this->payments()->create($datas);

            if (isset($datas['image'])){
                $payment->uploadFiles([$datas['image']]);
            }
            $result['success'] =  filled($payment);
            $result['message'] = __("Adding payment successfull");

        }else{
            $result['errors'] = $validation->errors()->all();
            $result['message'] = __("Failed to add payment");
        }

        return $result;
    }


    public function getBalanceAttribute(){
        return $this->payments()->availables()->get()->sum('remaining_amount') ?? 0;
    }

}
