<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

use App\Installment;

class OnetimeVerificationRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */

        private $parms;
        private $message;

    public function __construct($data)
    {
          $this->parms = $data;
          $this->setMessage("The  Amount is Invalid");

    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {  
        $percentage = $this->parms['percentage'];

        $sum_of_percentage = array_sum($percentage);
        $remaining_balance = $this->planVerification();

        if($sum_of_percentage <= 100)
        {
            
             $amount = $this->parms['amount'];


             

            for ($i = 0; $i < count($amount); $i++)
            {
                if($percentage[$i] > 0)
                {
                       $calculate_percentage = ($percentage[$i] /100);
                         
                       $calculate_amount = ($calculate_percentage * $remaining_balance);
                    
                      
                      if((int)$calculate_amount != (int)$amount[$i])
                      {
                         
                        $this->setMessage("The Amount is Invalid");
                        return false;


                      }
                      
                }
                else
                {
                    $this->setMessage("The Percentage is Invalid");
                        return false;

                }
               
                
            }

        
        }
        else
        {
            $this->setMessage("The Percentage is Invalid");
                        return false;

        }
        if(array_sum($this->parms['amount']) > $remaining_balance)
        {
            $this->setMessage("The Amount Sum is invalid");
                        return false;
        }

      
            return true;

     
    }

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

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

    public function planVerification()
    {
       
         try 
        {
            $booking_id = $this->parms['booking_id'];

            //DECRYPTING ENCRYPTED IDS
            $booking_id   = decrypt($booking_id);
           $installment = new Installment;
       return $installment->verificationPlan($booking_id);
           
        } 
        catch (DecryptException $e) 
        {
            
        }


    }
}
