<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use Schema;
use DB;
use Illuminate\Contracts\Encryption\DecryptException;

class InstallmentRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    private $booking_list;
    private $installment_list;
    private $message;


    public function __construct($booking,$installment)
    {
        $this->booking_list     = $booking;
        $this->installment_list = $installment;
        $this->message    = 'Required Validation.';
    }

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

            foreach ($this->booking_list as $rows) 
            {
                $booking     = decrypt($rows);

                $installment = decrypt($this->installment_list[$count]);

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

                        return false;
                    }
                }
                
                $count++;
            }

        } 
        catch (DecryptException $e) 
        {
            //
        }

        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    
    // SET ERROR MESSAGE
    public function setMessage($msg)
    {
        $this->message = $msg;
    }

    // RETURN CUSTOM ERROR MESSAGE
    public function message()
    {
        return $this->message;
    }

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

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

    
}
