<?php

namespace App\Http\Controllers\Administrator;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use DB;
use Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;
use Hash;
use App\Fun\Fun;
use App\ProvinceModel;
use App\DistrictModel;
use App\CommuneModel;
use App\VillageModel;
use App\SelectOptionModel;
use DataTables;
use Image;
use Illuminate\Support\Facades\Crypt;
class SuperAdminAgencyGroup extends Controller
{
//     function __construct()
//   {
//        $this->middleware('permission:Agency-Delete', ['only' => ['destroy']]);
//        $this->middleware('permission:Agency-Chart');
//        $this->middleware('permission:Agency-Create', ['only' => ['create','store']]);
//        $this->middleware('permission:Agency-Commission-Rate-List');
//        $this->middleware('permission:Agency-List');
//        $this->middleware('permission:Agency-Activated', ['only' => ['delete_agency']]);
//        $this->middleware('permission:Agency-Edit', ['only' => ['delete_agency']]);
//
//   }
    public function index()
    {
         $find_childs = User::where('parent_id', '=', 0)
         ->where('branch_id', \Branch::branch_id())
         ->orderBy('id','ASC')
         ->get();
        return view('administrator.agency.index',compact('find_childs'));
    }

    public function agencies_list(Request $request){
         $agencies_list = User::select("id","avatar","user_activity","agency_type","user_code","user_firstname","user_lastname","user_gender","user_phone","email","created_at","block_permission")
        ->where('role','Agencies')
        ->where('branch_id', \Branch::branch_id())
        ->orderBy('id','ASC')
        ->paginate(20);

        if ($request->ajax()) {
            return view('administrator.agency.r-agency-list', compact('agencies_list'));
        }
        return view('administrator.agency.agency-list', compact('agencies_list'));
    }

    public function delete_agency(Request $request, $id){
        $status = $request->status;
        $change_status = 0;
        if($status == 0){
            $change_status = 1;
        }else{
            $change_status = 0;
        }
        DB::table('users')
        ->where('id',$id)
        ->update(['user_activity'=> $change_status]);
        \LogActivity::addToLog('Disactived user successfully!');
        return redirect()->back();
    
    }
    public function create($Digit = 9)
    {
        $image = User::latest()->first();

        $log_id = Auth::user()->id;
        $agencys = User::select(
            DB::raw('CONCAT(user_code," / ",user_firstname," ",user_lastname) AS name_mixed'),'id')
            ->where('id','>','1')
            ->pluck('name_mixed','id')
            ->prepend('Please Select', '')
            ->toArray();
        $max = User::where('user_status',2)->max('user_code') + 1;
        $increas = $max+0;
        (string)$increas;
        while(strlen($increas) < $Digit){
            $increas = "0".$increas;
        }
        // echo json_encode($increas);
        // exit();
        $agencys = User::select(
            DB::raw('CONCAT(users.user_code," / ",users.user_firstname," ",users.user_lastname) AS name_mixed'),'users.id')
            ->join('nso007_funds','nso007_funds.user_id','users.id')
            ->where('users.id','>','1')
            ->pluck('name_mixed','users.id')
            ->prepend('Please Select', '')
            ->toArray();

        $select_option = SelectOptionModel::select(
                        DB::raw('CONCAT(id," ",title) AS option_mix'), 'id')
                        ->where('parent', 1)
                        ->where('status', 1)
                        ->pluck('option_mix', 'id')
                        ->prepend('Please Select', '');

        return view('administrator.agency.create',compact('increas','image','agencys', 'select_option'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $user = new User();
        $this->validate($request, [
            'agency_type' => 'required',
            'user_code'    => 'required|numeric|unique:users,user_code',
            'user_firstname'    => 'required',
            'user_lastname'     => 'required',
            'user_gender'   => 'required',
            'user_dob'  => 'required',
            'user_cardid'   => 'required|numeric|unique:users,user_cardid',
            'user_phone'    => 'required|unique:users,user_phone',
            'user_reference'    => 'required',
            'address'    => 'required',
            'email'     => 'required|email|max:255|unique:users,email',
            'password'  => 'required|same:confirm_password|string|min:8'
		
        ]);
        $file       = $request->file('image');
        if($request->file('image')== null){
            $original_name = "default.png";
        }else{
            $original_name = $file->getClientOriginalName();
            $original_name = date('ymdhis').$original_name;
            $destinationPath = 'assets/images/resize';
            $thum = Image::make($file->getRealPath())->resize(300, 300);
            $thum->save($destinationPath.'/'.$original_name,80);
           
        }
        if($request->parent_id == null){
            $parent_id   = 0;
        }else{
            $parent_id   = $request->parent_id;
        }
        
        $user->parent_id        = $parent_id;
        $user->agency_type      = $request->agency_type;
        $user->user_code        = $request->user_code;
        $user->user_firstname   = $request->user_firstname;
        $user->user_lastname    = $request->user_lastname;
        $user->user_gender      = $request->user_gender;
        $user->user_dob         = date('Y-m-d', strtotime($request->user_dob));
        $user->user_cardid      = $request->user_cardid;
        $user->user_phone       = $request->user_phone;
        $user->user_reference   = $request->user_reference;
        $user->address          = $request->address;
        $user->email            = $request->email;
        $user->user_activity    = 1;
        $user->role             = 'Agencies';
        $user->user_status      = 2;//Agency
        $user->user_activity    = 1;// Disative
        $user->branch_id        = \Branch::branch_id();
        $user->password         = Hash::make($request['password']);
        $user->avatar           = $original_name;
        $user->company_agent    = $request->company_agent;
        $user->save();
        
       \LogActivity::addToLog('Agency created successfully!');
        return redirect()->route('super-admin-agency.index')
        ->with('success','Agency created successfully');
       
    }

    public function show($id)
    {
        $decrypt_id = Crypt::decrypt($id);
        $find_childs = User::where('id', '=', $decrypt_id)->get();
       

        return view('administrator.agency.show',compact('find_childs'));
    }
    public function edit($id){


        $decrypt_id = Crypt::decrypt($id);
        $agencies = User::find($decrypt_id);
        
       
        $select_option = SelectOptionModel::select(
                        DB::raw('CONCAT(id," ",title) AS option_mix'), 'id')
                        ->where('parent', 1)
                        ->where('status', 1)
                        ->pluck('option_mix', 'id')
                        ->prepend('Please Select', '');
        return view('administrator.agency.edit',compact('agencies','select_option'));
    }
    public function update(Request $request, $id){
        
        $user = User::find($id);
        $this->validate($request, [
            'user_firstname'    => 'required',
            'user_lastname'     => 'required',
            'user_gender'   => 'required',
            'user_dob'  => 'required',
            'user_cardid'   => 'required|numeric|unique:users,user_cardid,'.$id,
            'user_phone'    => 'required|unique:users,user_phone,'.$id,
            'user_reference'    => 'required',
            'address'    => 'required',
            'email'     => 'required|email|max:255|unique:users,email,'.$id,
		
        ]);
        $oldImage = $request->hidden_image_name;
        if($request->file('image') == null){
            $file_name = $oldImage;
        }else{
            $newfile = $request->file('image');
            $file_name = $newfile->getClientOriginalName();
            if(file_exists(public_path().'/assets/images/resize'.$oldImage)){
                unlink(public_path().'/assets/images/resize'.$oldImage);
            }
            $file_name     = date('his'). $file_name ;
            $destinationPath = 'assets/images/resize';
            $get_img = Image::make($newfile->getRealPath())->resize(300, 300);
            $get_img->save($destinationPath.'/'.$file_name);
        }
       
        
        $user->user_firstname   = $request->user_firstname;
        $user->user_lastname    = $request->user_lastname;
        $user->user_gender  = $request->user_gender;
        $user->user_dob     = $request->user_dob;
        $user->user_cardid  = $request->user_cardid;
        $user->user_phone   = $request->user_phone;
        $user->user_reference = $request->user_reference;
        $user->address   = $request->address;
        $user->email    = $request->email;
        $user->role     = 'Agencies';
        $user->user_status     = 2;
        $user->user_activity     = $request->user_activity;
        $user->avatar  = $file_name;
        $input = $request->all();
        if(!empty($input['password'])){ 
            $input['password'] = Hash::make($input['password']);
        }else{
            $input = array_except($input,array('password'));    
        }
        $user->update($input);
        \LogActivity::addToLog('Agency updated successfully!');
        return redirect()->route('agencies.list')
        ->with('success','Agency updated successfully');
    }
	
	public function popup_view_agency(Request $request){
		$id = $request->id;
		$data = DB::select("SELECT 
					users.user_code,
					users.user_phone,
					users.user_gender,
					users.user_dob,
					users.user_cardid,
					users.avatar,
					users.user_reference,
					users.email,
					CONCAT(user_firstname, ' ', user_lastname) as full_name,
					users.address,
					nso007_bank.name as bank_name,
					nso007_agency_bank.account_name,
					nso007_agency_bank.account_number 
					FROM `users` 
					LEFT JOIN nso007_agency_bank ON users.id = nso007_agency_bank.agency_id
					LEFT JOIN nso007_bank ON nso007_bank.id = nso007_agency_bank.bank_id
                     where users.id = '$id'");
		echo json_encode($data);
		
	}
}
