<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use EF;

class PaymentVerficationRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    private $parms_list;
    private $message;

    public function __construct($parms)
    {
        $this->parms_list       = $parms;
        $this->message          = 'Required Validation.';
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $count = 0;
        $flag = false;

        try 
        {
            $branch = decrypt($this->parms_list[EF::branchWhiteLabel()['module']]);

            foreach ($this->parms_list['payment_type'] as $rows) 
            {
                $payment = decrypt($this->parms_list['payment_type'][$count]);
                $booking = decrypt($this->parms_list['booking'][$count]);



                $amount  = $this->parms_list['amount'][$count];

                if($payment > 0 )
                {
                    if($this->verification($booking,$payment,$amount,$branch) == 0)
                    {
                        $this->setMessage('The payment does not match against the booking');

                        return false;
                    }
                }


            
            }
        } 
        catch (DecryptException $e) 
        {
            //
        }

        return true;
    }

    public function verification($booking,$payment,$amount,$branch)
    {
        $condition = ['id' => $payment, 'booking_id' => $booking, 'amount' => $amount, 'is_recycle' => '0', 'branch_id' => $branch ];

        return (\DB::table('payments')->where($condition)->count());
    }

    public function setMessage($msg)
    {
        $this->message = $msg;
    }

    

    public function getPaymentList()
    {
        return $this->payment_list;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message;
    }
}
