<?php

namespace App\DataTables\Payments;

use App\Models\PaymentManagement\Payment;
use App\Models\PaymentManagement\PaymentMethod;
use App\Models\UserManagement\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\File;
use Illuminate\Validation\Rule;
use Yajra\DataTables\DataTablesEditor;

class PaymentDataTableEditor extends DataTablesEditor{
    protected $model = Payment::class;

    /**Get create action validation rules.
     * @return array
     */
    public function createRules(){
        $payment_table_name = $this->resolveModel()->getTable();
        $payment_method_table = (new PaymentMethod)->getTable();

        $data =  Arr::first(request()->get('data'));

        $paidAmount = $data['paid_amount'] ?? 0;
        $remainingAmount = $data['remaining_amount'] ?? 0;

        return  [
            "payment_method_id" => ['required',"int","exists:$payment_method_table,id"],
            "provider_reference" => [
                "required",'min:4',
                Rule::unique($payment_table_name,"provider_reference")
                    ->when(isset($data['payment_method_id']),function ($q) use($data){
                        return $q->where(function ($query) use($data){
                            return $query->where('payment_method_id',$data['payment_method_id']);
                        });
                    })
            ],

            "payer_number" => ['required',"numeric","min:4"],
            "paid_amount" => ['required',"numeric","min:1"],
            "remaining_amount" => [ "nullable","numeric","min:1","max:$paidAmount"],
            "paid_at" => [ "required","date",],
        ];
    }

    /**Get edit action validation rules.
     * @param Model $model
     * @return array
     */
    public function editRules(Model $model){
        $payment_table = $this->resolveModel()->getTable();
        $payment_method_table = (new PaymentMethod)->getTable();

        $data =  Arr::first(request()->get('data'));

        $paidAmount = $data['paid_amount'] ?? 0;
        $remainingAmount = $data['remaining_amount'] ?? 0;

        return  [
            "payment_method_id" => ['required',"int","exists:$payment_method_table,id"],
            "provider_reference" => ["required",'min:4',
                Rule::unique($payment_table,"provider_reference")
                    ->ignore($model->getKey())
                    ->when(isset($data['payment_method_id']),function ($q) use($data){
                        return $q->where(function ($query) use($data){
                            return $query->where('payment_method_id',$data['payment_method_id']);
                        });
                    })
            ],
            "payer_number" => ['required',"numeric","min:4"],
            "paid_amount" => ['required',"numeric","min:1"],
            "remaining_amount" => [ "nullable","numeric","max:$paidAmount"],
            "paid_at" => [ "required","date",],
        ];
    }

    /**
     * Get remove action validation rules.
     *
     * @param Model $model
     * @return array
     */
    public function removeRules(Model $model){
       // $role_table_name = $this->resolveModel()->getTable();
        return [
//            "ids" => ['required',"array","min:1"],
//            "ids.*" => ['required',"int","exists:$role_table_name,id,deleted_at,NULL"],
        ];
    }

    public function attributes(){
        return [
            "provider_reference" => __("Reference"),
            "payment_method_id" => __("Payment Method"),
            "paid_amount" => __("Paid Amount"),
            "paid_at" => __("Paid At"),
            "remaining_amount" => __("Remaining Amount"),
            "payer_number" => __("Payer Number"),
            "payer_id" => __("Payer"),
        ];
    }


    public function created(Payment $payment, $data){

        if (isset($data['image'])){
            $url = storage_path("app/public/".$data['image']);
            $payment->uploadFiles($url);

            if (filled($payment->media) and File::exists($url)){
                File::delete($url);
            }
        }
        return $payment;
    }

    public function updated(Payment $payment, $data){
        return $payment;
    }

    public function creating(Payment $payment, $data){

        $data['payer_type'] = (new User)->getMorphClass();

        if (isset($data['paid_at'])){
            $data['paid_at'] = format_date($data['paid_at'],'Y-m-d');
            $data['paid_at'] = date("Y-m-d H:i:s",strtotime($data['paid_at']));
        }
        return $data;
    }
}
