<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use App\Models\Material;
use Config;

class DeliveryOrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // echo 'DeliveryOrderController > index';       
        $user = auth()->user();
        $role = $user->getRole($user->id);
        $user_id     = $user->id;

        $res    = $user->getResidential($user->id);
        $residential_id = $res->residential_id;

        // $count  = DB::select("SELECT COUNT(id) as count FROM role_user WHERE FIND_IN_SET($id, residential_id)");        
        // $count  = $count[0]->count;        
        // if($count == 0) {
        //     dd("Permission not allow for the project");           
        // }
        
        $residential = DB::select("SELECT * FROM residential WHERE id IN ($residential_id) order by name asc");           

        return view('do.index', compact('residential', 'user', 'role'));
    }
	
	public function getDoList(Request $request) {
        // dd($request);
        $user    		= auth()->user();
        $role    		= $user->getRole($user->id);
        $user_id 		= $user->id;

        $res            = $user->getResidential($user->id);
        $residential_id = $res->residential_id;
        $company_id     = $res->company_id;

        $materials 		= Material::getMaterial('trade', $company_id);
        $user_info		= "";
        // dd($request);

        ## Read value
        $draw           = $request->get('draw');
        $start          = $request->get("start");
        $rowperpage     = $request->get("length"); // Rows display per page

        $columnIndex_arr= $request->get('order');
        $columnName_arr = $request->get('columns');
        $order_arr      = $request->get('order');
        $search_arr     = $request->get('search');

        $columnIndex    = $columnIndex_arr[0]['column']; // Column index
        $columnName     = $columnName_arr[$columnIndex]['data']; // Column name
        $columnSortOrder= $order_arr[0]['dir']; // asc or desc
        $searchValue    = $search_arr['value']; // Search value      

        $project_id     = $request['project_id'];
        $by_status      = $request['by_status'];
        $source      	= $request['source'];
		$action			= "";

        switch($by_status) {
            case 'new'      	: $by_status = 1;
                break;
			case 'pending'      : $by_status = 2;
                break;
            case 'po' 			: $by_status = 3;
                break;
			case 'do' 			: $by_status = 4;
                break;
            case 'completed'    : $by_status = 5;
                break;
            case 'rejected'     : $by_status = 6;
                break;
        }
        

        // $columnIndex    = "";
        // $columnName     = "name";
        // $columnSortOrder= "asc";
        // $searchValue    = "a";

        // Total records
        $totalRecords           = DB::table(Config::get('constants.tables.do'))->select(DB::raw('COUNT(*) as allcount'))
                ->where('residential_id', '=', $project_id)
                // ->where('status', '=', $by_status)
                ->where('company_id', '=', $company_id)->value('allcount');  
        // Material::select('count(*) as allcount')->count();
        $totalRecordswithFilter = DB::table(Config::get('constants.tables.do'))->select(DB::raw('COUNT(*) as allcount'))
                ->where('residential_id', '=', $project_id)
                // ->where('status', '=', $by_status)
                // ->where('do_no', 'LIKE', '%'.$searchValue.'%')
				->value('allcount');  
        //Material::select('count(*) as allcount')->where('name', 'like', '%' .$searchValue . '%')->count();

        // Fetch records
        // $records = Material::orderBy($columnName,$columnSortOrder)
        // ->where('trade.name', 'like', '%' .$searchValue . '%')
        // ->select('trade.*')
        // ->skip($start)
        // ->take($rowperpage)
        // ->get();

        $records = DB::table(Config::get('constants.tables.do'))
			// ->orderBy($columnName,$columnSortOrder)
            ->where('residential_id', '=', $project_id)
            ->where('company_id', '=', $company_id)
            // ->where('status', '=', $by_status)
            // ->where('do_no', 'LIKE', '%'.$searchValue.'%')
			// ->skip($start)
			->take($rowperpage)->get();  

        $data_arr   = array();
        $num        = 1;

		if($records) {
			foreach($records as $record){
				$fid				= $record->id;
				$create_by         	= $record->create_by;
				$vendor_id         	= $record->vendor_id;
				$user_info	    	= DB::table(Config::get('constants.tables.user'))->select('name', 'tel')
					->where('id', '=', $create_by)->get();  
				
				if($vendor_id != 0) {
					$vendor_info	= DB::table(Config::get('constants.tables.vendor'))->select('company_name', 'tel')
						->where('id', '=', $vendor_id)->get();  
				} else {
					$vendor_info = array();
				}				
					
				$do_no     			= $record->do_no;
				$create_at          = $record->create_at;       
				$status 			= ($record->status == 1) ? "Pending" : "";
				
				switch($record->status) {
					case '1'	: $status = "Pending";
						break;
					case '2'	: $status = "Accepted";
						break;
					case '3'	: $status = "Processing";
						break;
					case '4'	: $status = '<label style="color:green;">Completed</label>';
						break;
					case '5'	: $status = '<label style="color:red;">Rejected</label>';
						break;
					// case '6'	: $status = "Rejected";
						// break;
					
				}
				
				$total_item         = DB::table(Config::get('constants.tables.do_item'))->select(DB::raw('COUNT(*) as allcount'))
					->where('do_id', '=', $fid)->value('allcount');
					
				// if($source == "po_page") {					
					// $action	= '<a href="#" class="btn btn-light-primary font-weight-bolder btnSelect" data-id="'.$fid.'">Select</a>';
				// } else {
					// $action = '<a href="'.$project_id.'/edit/'.$fid.'" class="action-btn"><i class="fas fa-edit" data-id="'.$fid.'"></i></a>';
				// }
				
				if($record->status == 1) {
					$action	= '<a href="#" class="btn btn-light-success font-weight-bolder btnUpdateAction" data-toggle="modal" data-target="#ConfirmPopup" data-id="'.$fid.'" data-ref-no="'.$do_no.'" data-action="accept" >Accept</a>
					<a href="#" class="btn btn-light-danger font-weight-bolder btnUpdateAction" data-toggle="modal" data-target="#ConfirmPopup" data-id="'.$fid.'" data-ref-no="'.$do_no.'" data-action="reject" >Reject</a>';
				} else {
					$action = '-';
				}
					
				$data_arr[] = array(
					"id"                => '',            
					"do_no"				=> '<a class="modal-links do" data-toggle="modal" data-target="#do_form" data-id="'.$fid.'">'.$do_no.'</a>',	//$requisition_no,
					"total_item"        => $total_item,              
					"create_by"         => $user_info[0]->name,
					"create_at"         => $create_at,
					"vendor"           	=> ($vendor_info) ? $vendor_info[0]->company_name : array(),
					"rf_no"            	=> "",
					"do"            	=> "",
					"status"            => $status,					
					// "action"            => $action
					// "action"    => '<a href="#" class="action-btn" data-toggle="modal" data-target="#edit_Item"><i class="fas fa-edit" data-id="'.$id.'"></i></a>'
				);

				$num++;
			}
		}
       
        $response = array(
            "draw"                  => intval($draw),
            "iTotalRecords"         => $totalRecords,
            "iTotalDisplayRecords"  => $totalRecords,
            // "iTotalDisplayRecords"  => $totalRecordswithFilter,
            "aaData"                => $data_arr,
			"user_info"				=> $user_info
        );
        
        echo json_encode($response);
        exit;        
    }

	public function update_status(Request $request, $id) {
		define("TABLE_DO", Config::get('constants.tables.do'));
		define("TABLE_DO_ITEM", Config::get('constants.tables.do_item'));
		define("TABLE_INVENTORY", Config::get('constants.tables.inventory'));
		define("TABLE_INVENTORY_LOG", Config::get('constants.tables.inventory_log'));
		define("TABLE_ITEM", Config::get('constants.tables.item'));
		
		$user       = auth()->user();
        $user_id    = $user->id;
        $res        = $user->getResidential($user->id);
        $company_id = $res->company_id;
       
        $project_id 	= $request['project_id'];
        $list       	= $request['list'];               
        $do_no      	= $request['do_no'];
        $do_file      	= $request['do_file'];
        $vendor_id      = $request['vendor_id'];
        $update_status  = $request['update_status'];
        $remark  		= $request['remark'];
        $update_result 	= "";
		$status			= "";
		$msg			= "";
		$do_id			= $id;
		$inventory_id	= "";

		// DB::enableQueryLog();
        $residential = DB::select("SELECT * FROM ".Config::get('constants.tables.residential')." WHERE id = '$project_id' AND company_id = '$company_id'")[0];       
       
        if($residential == false) {
            $msg = "[residential][project_id: $project_id] [company_id: $company_id] Invalid request.";
            return response()->json(['status' => 'fail', 'msg' => $msg, 'request'=>$request->all()]);
            exit;
        }
		
		$data_row = array();
		
		if($update_status == "accept") {
			$data_row['status']         = 2;
			$data_row['accept_by']      = $user_id;
			$data_row['accept_at']      = date("Y-m-d H:i:s");
			
		} else if($update_status == "reject") {
			$data_row['status']         = 5;
			$data_row['reject_by']      = $user_id;
			$data_row['reject_at']      = date("Y-m-d H:i:s");	
		}
		
		if($remark != "") {
			$data_row['remark']      = DB::raw("CONCAT(remark, '\n[".strtoupper($update_status)."] ', '$remark')");
		}
		
		$update_result = DB::table(Config::get('constants.tables.do'))->where('id', '=', $id)->update($data_row);
		
		if($update_status == "accept") {
			$do_item_list	= DB::table(TABLE_DO_ITEM)
				->select(TABLE_DO_ITEM.'.qty', TABLE_DO_ITEM.'.remark', TABLE_DO_ITEM.'.item_id', TABLE_ITEM.'.name', TABLE_ITEM.'.description', TABLE_ITEM.'.unit', TABLE_ITEM.'.img')
				->leftJoin(TABLE_ITEM, TABLE_DO_ITEM.'.item_id', '=', TABLE_ITEM.'.id')
				->leftJoin(TABLE_DO, TABLE_DO_ITEM.'.do_id', '=', TABLE_DO.'.id')
				->where(TABLE_DO.'.id', '=', $do_id)
				->where(TABLE_DO.'.company_id', '=', $company_id)
				->where(TABLE_DO.'.residential_id', '=', $project_id)
				->orderBy(TABLE_DO_ITEM.'.id', 'asc')
				->get();
			
			foreach($do_item_list as $item) {
				$item_id 		= $item->item_id;
				$item_unit		= ($item->unit == "") ? "-" : $item->unit;
				$item_qty		= $item->qty;
			
				$inventory	= DB::table(TABLE_INVENTORY)->select(DB::raw('COUNT(*) as count, qty, id'))
					->where('company_id', '=', $company_id)
					->where('residential_id', '=', $project_id)
					->where('item_id', '=', $item_id)
					->first();
					// ->whereRaw('Date(create_at) = CURDATE()')->value('count');
					
				$inventory_id	= $inventory->id;
				$count_item		= $inventory->count;
				$last_qty		= ($inventory->qty > 0) ? $inventory->qty : "0";
				
				$data_row = array();
				if($count_item == 0) {
					$data_row['company_id']     = $company_id;
					$data_row['residential_id'] = $request['project_id'];
					$data_row['item_id'] 		= $item_id;
					$data_row['unit'] 			= $item_unit;
					$data_row['qty'] 			= $item_qty;					
					$data_row['status']         = 1;					
					$data_row['create_by']      = $user_id;
					$data_row['create_at']      = date("Y-m-d H:i:s");

					$inventory_id = DB::table(TABLE_INVENTORY)->insertGetId($data_row);
					
				} else {
					$data_row['qty']      	= DB::raw("qty + $item_qty");
					$data_row['update_by']	= $user_id;
					$data_row['update_at']	= date("Y-m-d H:i:s");
					
					if($inventory_id != "") {
						$update_result = DB::table(TABLE_INVENTORY)
							->where('company_id', '=', $company_id)            
							->where('residential_id', '=', $project_id) 
							->where('id', '=', $inventory_id) 
							->where('item_id', '=', $item_id)								
							->update($data_row);
					}
				}
				
				$data_temp = array();
				if($inventory_id || $inventory_id != "") {
					$data_temp['inventory_id']	= $inventory_id;
					$data_temp['do_id'] 		= $do_id;
					$data_temp['item_id']		= $item_id;						
					$data_temp['qty']			= $item_qty;					
					$data_temp['last_qty']		= $last_qty;									
					$data_temp['type']			= "add";									
					$data_temp['create_by']		= $user_id;
					$data_temp['create_at']		= date("Y-m-d H:i:s");

					DB::table(TABLE_INVENTORY_LOG)->insert($data_temp);
				}
			}
		}
		
		// DB::table(Config::get('constants.tables.do'))
			// ->where('id', '=', $id)
			// ->update([
				// 'remark'	=> DB::raw("CONCAT(remark, '\n', '$remark')")
			// ]);
		
		if($update_result) {
			$status = "success";
		} else {
			$status = "fail";
			$msg 	= "Failed to update.";
		}
		// dd(DB::getQueryLog());
		return response()->json(['status' => $status, 'msg' => $msg, 'request'=>$request->all(), 'do_id'=>$id]);
	}
	
	public function getDoDetail(Request $request) {
        // dd($request);
		define("TABLE_COMPANY", Config::get('constants.tables.company'));
		define("TABLE_ITEM", Config::get('constants.tables.item'));
		define("TABLE_DO", Config::get('constants.tables.do'));
		define("TABLE_DO_TEM", Config::get('constants.tables.do_item'));		
		define("TABLE_PO", Config::get('constants.tables.po'));
		define("TABLE_RESIDENTIAL", Config::get('constants.tables.residential'));
		define("TABLE_USER", Config::get('constants.tables.user'));		
		define("TABLE_VENDOR", Config::get('constants.tables.vendor'));		
		
        $user    		= auth()->user();
        $role    		= $user->getRole($user->id);
        $user_id 		= $user->id;

        $res            = $user->getResidential($user->id);
        $residential_id = $res->residential_id;
        $company_id     = $res->company_id;
		$vendor_id	 	= $res->vendor_id;

        $materials 		= Material::getMaterial('trade', $company_id);		
		$residential 	= DB::select("SELECT * FROM ".Config::get('constants.tables.residential')." WHERE id IN ($residential_id) order by name asc"); 
		
		$status 		= "fail";
		$project_id     = $request['project_id'];
		$do_id     		= $request['id'];		
		$do_detail		= "";
		$do_list		= array();
		
		$company_info	= DB::table(TABLE_COMPANY)
			->select(TABLE_COMPANY.'.id AS company_id', TABLE_COMPANY.'.name AS company_name', TABLE_COMPANY.'.address AS company_addr', TABLE_RESIDENTIAL.'.name AS residential_name', TABLE_RESIDENTIAL.'.address AS residential_addr', TABLE_RESIDENTIAL.'.logo')
			->leftJoin(TABLE_RESIDENTIAL, TABLE_RESIDENTIAL.'.company_id', '=', TABLE_COMPANY.'.id')
            ->where(TABLE_COMPANY.'.id', '=', $company_id)
            ->where(TABLE_RESIDENTIAL.'.id', '=', $project_id)
            ->get(); 
		
		if($company_info && count($company_info) > 0) {
			$status = "success";
		} 
		// DB::enableQueryLog();
		$do_detail 	= DB::table(TABLE_DO)
			->select(TABLE_DO.'.*', TABLE_USER.'.name AS creator_name', TABLE_USER.'.tel AS creator_tel', TABLE_VENDOR.'.company_name AS vendor_company', TABLE_VENDOR.'.address AS vendor_addr', TABLE_PO.'.po_no')
			->leftJoin(TABLE_USER, TABLE_USER.'.id', '=', TABLE_DO.'.create_by')
			->leftJoin(TABLE_VENDOR, TABLE_VENDOR.'.id', '=', TABLE_DO.'.vendor_id')
			->leftJoin(TABLE_PO, TABLE_PO.'.id', '=', TABLE_DO.'.po_id')			
            ->where(TABLE_DO.'.id', '=', $do_id)
            ->where(TABLE_DO.'.company_id', '=', $company_id)
            // ->where(TABLE_DO.'.vendor_id', '=', $vendor_id)           
            ->get();		
				
		$do_list[]	= DB::table(TABLE_DO_TEM)
			->select(TABLE_DO_TEM.'.qty', TABLE_DO_TEM.'.remark', TABLE_DO_TEM.'.item_id', TABLE_DO_TEM.'.id AS do_item_id', TABLE_DO_TEM.'.po_item_id AS po_item_id', TABLE_ITEM.'.name', TABLE_ITEM.'.description', TABLE_ITEM.'.unit', TABLE_ITEM.'.img')
			->leftJoin(TABLE_ITEM, TABLE_DO_TEM.'.item_id', '=', TABLE_ITEM.'.id')
			->leftJoin(TABLE_DO, TABLE_DO_TEM.'.do_id', '=', TABLE_DO.'.id')
            ->where(TABLE_DO.'.id', '=', $do_id)
            ->where(TABLE_DO.'.company_id', '=', $company_id)
            // ->where(TABLE_DO.'.vendor_id', '=', $vendor_id)
			->orderBy(TABLE_ITEM.'.name', 'desc')            
            ->get();

		
		 echo json_encode(array('status' => $status, 'company_info' => $company_info, 'do_detail' => $do_detail, 'do_list' => $do_list, 'request'=>$request));
	}
	 

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        // echo 'DeliveryOrderController > show';       
        $user = auth()->user();
        $role = $user->getRole($user->id);
        $user_id     = $user->id;

        $res    = $user->getResidential($user->id);
        $residential_id = $res->residential_id;

        $count  = DB::select("SELECT COUNT(id) as count FROM role_user WHERE FIND_IN_SET($id, residential_id) AND user_id = '$user_id'");        
        $count  = $count[0]->count;        
        if($count == 0) {
            // dd("Permission not allow for the project");
			return redirect('/login');
        }
        
        $residential = DB::select("SELECT * FROM residential WHERE id IN ($residential_id) order by name asc");
		
		if(Gate::check('is-site')) {
			return view('site.do', compact('residential', 'user', 'role'));
		}

        return view('do.index', compact('residential', 'user', 'role'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
