<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\User;
use App\CreditRegister;
use App\Http\Requests\CreditRegisterRequest;
use Auth;

class CreditRegisterController extends Controller
{

	public function __construct()
    {
        $this->middleware('auth');
    }
    public function index(Request $user)
    {		dd($user);		
			if(Auth::user()->role->role_permission('view_credit')){
							dd($user);						if(Auth::user()->role->role_permission('view_credit')->level == 'all'){
					$creditregister = CreditRegister::where('user_id',$user->id)->paginate(30);
					$userId = $user->id;
				}
				return view('creditregister.index', compact('creditregister','userId'));
			}else{
				abort(403);
			}
    }
		
		public function store(Request $request)
		{
					
			$startDate = date_parse_from_format("Y-m-d", $request->startDate);
			$endDate = date_parse_from_format("Y-m-d", $request->endDate);
			$date_month_start = $startDate["month"];
			$date_year_start = $startDate["year"];
			$date_month_end = $endDate["month"];
			$date_year_end = $endDate["year"];
			$boat_id = $request->boat_id;
			$customer = $request->customer_id;
			$mode = $request->m;
			if ($mode == 3) {
				$morning = 1;
				$afternoon = 1;
			} else {
				$festivo_morning = 1;
				$festivo_afternoon = 1;
			}
			$total_months = ($date_year_end - $date_year_start)*12 + ($date_month_end  - $date_month_start) + 1;
			if(Auth::user()->role->role_permission('create_credit')){
				$current_month = $date_month_start;
				$current_year = $date_year_start;
				for ($i = 0; $i < $total_months; $i++) {
					if ($current_month  > 12) {
						$current_month = 1;
						$current_year += 1;
					}
					$alternancia = $i % 2;
					if ($mode == 3) {
						$festivo_morning = 1 - $alternancia;
						$festivo_afternoon = $alternancia;
					} else {
						$morning = 3 - $alternancia;
						$afternoon = $alternancia + 2;
					}
					$data = [
						'boat_id' => $boat_id,
						'customer_id' => $customer,
						'date_month' => $current_month,
						'date_year' => $current_year,
						'festivo_morning' => $festivo_morning,
						'festivo_afternoon' => $festivo_afternoon,
						'morning' => $morning,
						'afternoon' => $afternoon,
					];
$deleted =  CreditRegister::where('boat_id', $boat_id)
						->where('customer_id', $customer)
						->where('date_month', $current_month)
						->where('date_year', $current_year)
						->delete();
	
			$credituser = CreditRegister::create($data);
					$current_month += 1;
				}

				return redirect('credits/'.$customer.'/assign')->withSuccess('Creditos assignados correctamente.');
			} else {
				abort(403);
			}
		}
		
			
}