<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Item;
use App\Department;
use App\PurchaseRequest;
use App\MaterialIssueRequest;
use Illuminate\Support\Facades\Auth;
use App\MaterialIssueRequestData;
use App\ItemPurchaseRequest;
use App\ReceiptItem;
use App\ItemRelease;
use App\Role;
use App\MaterialRequestApproval;
use App\User;

class MaterialIssueRequestController extends Controller
{
    public function __construct()
    {
           
    }

    function index()
    {
        $approvalCount = array();
        $cancelCount = array();
         $user = User::with('role')->find(Auth::user()->id);

       $role =   Role::find($user->role->role_id);

        if ($role->name == 'admin') 
        {
        $material_issue_requests = MaterialIssueRequest::with(['requestingItems' , 'department'])->orderBy('id', 'DESC')->get();
        }
        else
        {
        $material_issue_requests = MaterialIssueRequest::where('request_person_name' , $user->name)->with(['requestingItems' , 'department'])->orderBy('id', 'DESC')->get();
        }
        

        $departments = Department::orderBy('department_name')->get();
        $purchase_requests = PurchaseRequest::where('status'  , 7)->orderBy('id')->get(['id']);
        $items = Item::orderBy('item_name' , 'ASC')->where('type' , '!=' , 'tools')->get(['id','item_name']);
        $approval_roles = Role::orderBy('id', 'DESC')->get(['id','name']);

        foreach($material_issue_requests as $list)
        {
            $approvalCount[$list->id] = MaterialRequestApproval::where('mir_id' , $list->id)->where('is_approve' , MaterialRequestApproval::upapprove) ->count();
            $cancelCount[$list->id] = MaterialRequestApproval::where('mir_id' , $list->id)->where('is_approve' ,  MaterialRequestApproval::cancel) ->count();
        }

        return view('procurement/mir.index' ,compact('material_issue_requests' , 'departments' , 'purchase_requests','items','approval_roles','approvalCount','cancelCount'));
    }

    public function requesting(Request $request)
{


    $releaser_name = $request->releaser_name;
    $date =  $request->date;
    $purchase_request_id =  $request->purchase_requests_id;
    $department =  $request->department;
    $items =  $request->items;
    $type =  $request->type;
    $is_with_pr = $request->is_with_pr;

     if( empty($items))
    {
        echo json_encode(array('response' => 'invalid' , 'message' => 'No Items Found For This Purchase Request.'));
        exit();
    }

    if( empty($releaser_name))
    {

        echo json_encode(array('response' => 'invalid' , 'message' => 'Please Enter Valid  Name.'));
        exit();
    }

      if(empty($date) && (strtotime($date) < strtotime(date('Y-m-d'))  ))
    {
        echo json_encode(array('response' => 'invalid' , 'message' => 'Please Select Valid Date.'));
        exit();
    }

    if($purchase_request_id == null || !is_numeric($purchase_request_id))
    {
    echo json_encode(array('response' => 'invalid' , 'message' => 'Please Select Valid Purchase Request.'));
    exit();
    }

    if(empty($department) || !is_numeric($department))
    {
    echo json_encode(array('response' => 'invalid' , 'message' => 'Please Enter Valid Department Name.'));
    exit();
    }

    if( in_array("0", array_column($items, 'item_id')) || in_array("0", array_column($items, 'releasing_quantity')) || !array_filter(array_column($items, 'releasing_quantity')) || !array_filter(array_column($items, 'item_id'))  )
    {
    echo json_encode(array('response' => 'invalid' , 'message' => 'Please Enter Valid Item Quantity. Quantity Not be Empty Or Zero.'));
    exit();
    }


    if ($is_with_pr == 'false'  && empty($request->approval_roles)) 
    {  
    echo json_encode(array('response' => 'invalid' , 'message' => 'Please Enter Roles For Approval.'));
    exit();
    }


   DB::beginTransaction();

   try {

            $item_releasing_array = [
            'pr_id' => $purchase_request_id,
            'department_id' =>  $department
            ];

            $item_releasing_array['request_person_name'] = $releaser_name;
            $item_releasing_array['request_date'] = date('Y-m-d' , strtotime($date));
            $item_releasing_array['description'] = $request->note;

            if ($is_with_pr == 'false' ) 
            {
                $item_releasing_array['mir_type'] = MaterialIssueRequest::without_purchase_request;
            }
       
            $item_request = MaterialIssueRequest::create($item_releasing_array );


             if ($is_with_pr == 'false' ) 
            {
                     MaterialRequestApproval::create(['approval_id' => $request->approval_roles , 'mir_id' => $item_request->id , 'is_approve' => MaterialRequestApproval::upapprove ]);
                
            }


        for ($i= 0; $i < sizeof($items); $i++) 
       { 
           $itemId =  $items[$i]['item_id'];
           $releasing_quantity =  $items[$i]['releasing_quantity'];

           $item_data = Item::where('id' , $itemId);
           $item =  $item_data->first();

        if ($is_with_pr == 'false' && ($item->quantity < $releasing_quantity)) 
        {
            DB::rollback();
            echo json_encode(array('response' => 'invalid' , 'message' => 'Only <b>'.$item->quantity.'</b> quantity left for item <b>'.$item->item_name.'</b> and you enter <b>'.$releasing_quantity.'</b>. '));
            exit();
        }

        if ($purchase_request_id > 0)
        {

        $demand_item_quantity = ItemPurchaseRequest::where('purchase_request_id', '=', $purchase_request_id)
        ->where( 'item_id', $itemId)
        ->first()->quantity;

        $total_receive_items = ReceiptItem::where('purchase_request_id' , $purchase_request_id)
        ->where('approval_status' , 'approve')
        ->where('pass_quantity' , '>' , 0)
        ->where('item_id' ,  $itemId)
        ->sum('pass_quantity');

        $current_requesting = 0;
        
        $current_returning = 0;
      

        $current_return = ItemRelease::where('purchase_request_id', $purchase_request_id)
        ->each(function($p, $k) use (&$current_returning , &$itemId) 
        {
            
            $current_returning += $p->releasingItems()->where('item_id' , $itemId)->sum('return_quantity');
        });

        $current_release = MaterialIssueRequest::where('pr_id', $purchase_request_id)
        ->each(function($p, $k) use (&$current_requesting , &$itemId) 
        {
            $current_requesting += $p->requestingItems()->where('item_id' , $itemId)->sum('item_requesting_quantity');
        });

          $current_requesting =  $current_requesting  - $current_returning;


        if ($releasing_quantity > $demand_item_quantity ) 
        {
            DB::rollback();
            echo json_encode(array('response' => 'invalid' , 'message' => 'Demand Quantity of  item <b>'.$item->item_name.'</b> is '.$demand_item_quantity.' and you enter invalid quantity  <b>'.$releasing_quantity.'</b>. '));
            exit();
        }

         if ($type == 'false' && ($releasing_quantity > ($total_receive_items - $current_requesting)) ) 
        {
            DB::rollback();
            echo json_encode(array('response' => 'invalid' , 'message' => 'You Already request '.$current_requesting.' Quantity of  item <b>'.$item->item_name.'</b> and now you can only request for quantity <b>'.($total_receive_items - $current_requesting).'</b>. '));
            exit();
        }

        
        }

        $item_request_data_array = [
        'mir_id' =>  $item_request->id,
        'item_id' => $itemId,
        ];

        if( !empty($releasing_quantity) )
        {
             $item_request_data_array['item_requesting_quantity'] =  $releasing_quantity;
              MaterialIssueRequestData::create($item_request_data_array ); 
        }


    }

      DB::commit();

      echo json_encode(array('result' => 'valid' , 'message' => 'Mir Created Successfully.'));
   
      } 
        catch (\Exception $e) 
      {
        DB::rollback();
dd($e);
        echo json_encode(array('response' => 'invalid' , 'message' => 'Something Went Wrong Data.'));
      }
             
}

public function destroy($id  = null)
{
  
    MaterialIssueRequest::where('id' , $id)->delete();
    MaterialIssueRequestData::where('mir_id' , $id)->delete();

    return redirect()->route('material.issue.request.list')->with('success' , 'Removed Successfully!');
}

public function getMirItem(Request $request)
{
    $id = $request->id;
    $data = array();
    $mir = MaterialIssueRequest::find($id);
    
    if ($mir == true) 
    {
        foreach ($mir->requestingItems as $key => $value) 
        {
            $item = Item::find($value->item_id);

            $data[] = array('item_name' => $item->item_name , 'request_quntity' => number_format($value->item_requesting_quantity , 2) , 'status' =>  Ucfirst($mir->status) );
        }

      echo   json_encode( array('response' => 'yes' , 'output' => $data , 'note' => $mir->description));
    } 
}


    public function approveMir(Request $request , $mir_id = null)
    {
        MaterialRequestApproval::where('mir_id' ,  $mir_id )->where('approval_id' , $request->user)->update(['is_approve' => MaterialRequestApproval::approve]); 
        return redirect()->back()->with('success-mir' , 'Approved Successfully!');
    }

    public function cancelMir(Request $request , $mir_id = null)
    {
        MaterialRequestApproval::where('mir_id' ,  $mir_id )->where('approval_id' , $request->user)->update(['is_approve' => MaterialRequestApproval::cancel]); 
        return redirect()->back()->with('success-mir' , 'Cancel Successfully!');
    }


}
