<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class LoopGroupRule implements Rule
{
    /**
     * Create a new rule instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        foreach ($value as $key => $v) {

            if( ! (float)$v['max_budget'] ) {
                return false;
            }
            $hold= 0;
            $release= 0;
            foreach ($v['months'] as $k => $month) {
                // In the first month there is no money in the savebox, so the release value must be 0
                if($k == 0 && $month['release'] > 0) {
                    return false;
                }

                // In the last month no money should be saved in the savebox, so the hold value must be 0
                if($k+1 == count($v['months']) && $month['hold'] > 0) {
                    return false;
                }

                $hold += $month['hold'];
                $release += $month['release'];

                if( $month['hold'] < 0 || $month['release'] < 0 ||
                 $month['hold'] > 100 || $month['release'] > 100 ||
                 $month['fees'] < 0 || $month['score'] < 0) {

                    return false;
                }
            }
            // dd($hold, $release);
            if( $hold - $release != 0 ) {
                // dd($key, $hold, $release);
                return false;
            }
        }
        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return __('settings.group_setting_error');
    }
}
