<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;
use App\Installment;

class UpdateInstallmentRule 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)
    {
        $amount = $this->parms['amount'];

        $remaining_balance = $this->planVerification();

        if(($amount > 0 && $remaining_balance > 0)  && $amount <= $remaining_balance)
        {
             
        }
        else
        {
             $this->setMessage("The amount is greater than plan amount");
                     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 
        {
   
            $installment_id = $this->parms['id'];

           
            $laging_amount = 0;

            //DECRYPTING ENCRYPTED IDS
            $installment_id   = decrypt($installment_id);

            $installment      = new Installment;

            $curr_installment = $installment->getInstallmentById($installment_id);


            if(isset($curr_installment->id))
            {
                $remaining_paid_balance = $installment->sumPaidBalance($curr_installment->booking_id,'Paid');

                $remaining_plan_amount = $installment->verificationPlan($curr_installment->booking_id);

                $laging_amount = $curr_installment->amount - $curr_installment->received_amount;

                if(($remaining_paid_balance + $remaining_plan_amount) > 0)
                {
                    $laging_amount += ($remaining_paid_balance + $remaining_plan_amount);
                }
                
   
            }

            return $laging_amount;

           

          // return $installment->updateVerificationPlan($installment_id);
           
        } 
        catch (DecryptException $e) 
        {
            
        }


    }
}
