<?php

namespace App\Http\Controllers\Administrator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

use App\BranchModel;
use GuzzleHttp\Client;
use Image;
use Illuminate\Support\Facades\Crypt;
use App\User;
use Hash;
use App\AssingBranchModel;
use Spatie\Permission\Models\Role;
use DB;
class BranchController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
   function __construct()
   {
        $this->middleware('permission:Branch-List');
        $this->middleware('permission:Branch-Create', ['only' => ['create','store']]);
        $this->middleware('permission:Branch-Edit', ['only' => ['edit','update']]);
        $this->middleware('permission:Branch-View-Info', ['only' => ['show']]);
        $this->middleware('permission:Branch-Assign-Branch', ['only' => ['assign_branch']]);
   }
    
    public function index()
    {
        // $url_api = 'https://license.nsohosting.com/public/api/verify/product';
        // $param['body'] = json_encode([
        //     'key_code' => 'KEY-NSO-051218-01',
        // ]);

        // $http_client = $client = new Client([
        //     'verify' => false,
        //     'headers' => [
        //         'Content-Type' => 'application/json',
        //     ]
        // ]);
        // $response = $http_client->post($url_api, $param);

        // $json = $response->getBody();
        // $buyed = json_decode($json);
        $buyed = "";
        $branches = BranchModel::all();
        return view('administrator.branches.index',compact('branches','buyed'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $branches = BranchModel::all();
        if(count($branches)>4) return \back()->with("warning","Branch can't create more than 4 ! Please contact developer for purchase more branch.");
        return view('administrator.branches.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $branches = BranchModel::all();
        if(count($branches)>4) return \back()->with("warning","Branch can't create more than 4 ! Please contact developer for purchase more branchs.");
        $this->validate($request, [
            'branch_en'       => 'required',
            'branch_kh'             => 'required',
            'branch_phone'    => 'required',
            'branch_email'    => 'required',
            // 'image'     => 'dimensions:height=80,width=180',
        ]);

        // $url_api = 'https://license.nsohosting.com/public/api/verify/product';
        // $param['body'] = json_encode([
        //     'key_code' => 'KEY-NSO-051218-01',
        // ]);

        // $http_client = $client = new Client([
        //     'verify' => false,
        //     'headers' => [
        //         'Content-Type' => 'application/json',
        //     ]
        // ]);
        // $response = $http_client->post($url_api, $param);

        // $json = $response->getBody();
        // $buyed = json_decode($json);
        
        // $current_branch = BranchModel::whereNull('key_code')->count();

        $this->validate($request, [
        ]);

        $branches_model = new BranchModel;
        $branches_model->branch_en     = $request->branch_en;
        $branches_model->branch_kh     = $request->branch_kh;
        $branches_model->branch_phone     = $request->branch_phone;
        $branches_model->branch_email     = $request->branch_email;
        $branches_model->branch_address     = $request->branch_address;
        $branches_model->branch_note     = $request->branch_note;

        $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());
            $thum->save($destinationPath.'/'.$original_name,80);
            $destinationPath = 'assets/images/original';
            $file->move($destinationPath,$original_name);
        }

        $branches_model->branch_img  = $original_name;
        $branches_model->save();
        \LogActivity::addToLog('Branches created successfully !');
        return redirect()->route('branches.index')
            ->with('success','Branches created successfully !');

        // if($current_branch < $buyed){
        //     $branches_model = new BranchModel;
        //     $branches_model->branch_en     = $request->branch_en;
        //     $branches_model->branch_kh     = $request->branch_kh;
        //     $branches_model->branch_phone     = $request->branch_phone;
        //     $branches_model->branch_email     = $request->branch_email;
        //     $branches_model->branch_address     = $request->branch_address;
        //     $branches_model->branch_note     = $request->branch_note;

        //     $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());
        //         $thum->save($destinationPath.'/'.$original_name,80);
        //         $destinationPath = 'assets/images/original';
        //         $file->move($destinationPath,$original_name);
        //     }

        //     $branches_model->branch_img  = $original_name;
        //     $branches_model->save();
        //     \LogActivity::addToLog('Branches created successfully !');
        //     return redirect()->route('branches.index')
        //         ->with('success','Branches created successfully !');



        // }else{

        //     \LogActivity::addToLog('Branch Can not Create');
        //     return redirect()->route('branches.create')
        //         ->with('danger','Please Contact to Admin NET SOLUTION ONLINE !');

        // }
        
       
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $decrypt_id = Crypt::decrypt($id);
        // $branches = BranchModel::find($decrypt_id);

        $branches = DB::table('nso007_branches')
        ->leftJoin('nso007_assign_branches', 'nso007_branches.id', '=', 'nso007_assign_branches.branch_id')
        ->leftJoin('users', 'users.id', '=', 'nso007_assign_branches.user_id')
        ->where('nso007_branches.id',$decrypt_id)
        ->get();



       return view('administrator.branches.show',compact('branches'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $decrypt_id = Crypt::decrypt($id);
        $branches = BranchModel::find($decrypt_id);
        return view('administrator.branches.edit',compact('branches'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $branches = BranchModel::find($id);
       
        $this->validate($request, [
            'branch_en'       => 'required',
            'branch_kh'             => 'required',
            'branch_phone'    => 'required',
            'branch_email'    => 'required',
            // 'image'     => 'dimensions:height=80,width=180',
        ]);

        $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());
            $get_img->save($destinationPath.'/'.$file_name);
        }
        $branches->branch_img       = $file_name;
        $branches->branch_en     = $request->branch_en;
        $branches->branch_kh     = $request->branch_kh;
        $branches->branch_phone     = $request->branch_phone;
        $branches->branch_email     = $request->branch_email;
        $branches->branch_address     = $request->branch_address;
        $branches->branch_note     = $request->branch_note;

       
        $branches->update();
        

        \LogActivity::addToLog('Bank updated successfully !');
        return redirect()->route('branches.index')
                        ->with('success','bank updated successfully !');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function assign_branch($id)
    {
        $decrypt_id = Crypt::decrypt($id);
        $branches = BranchModel::find($decrypt_id);
        $roles = Role::where('name','Branches Management')->pluck('name','name')->all();

        return view('administrator.branches.assign-branch',compact('branches','roles'));
    }

    public function store_branch(Request $request){
       
    {
        $user = new User;
        $this->validate($request, [
            
            'user_firstname'    => 'required',
            'user_lastname'     => 'required',
            'user_gender'   => 'required',
            'user_phone'    => 'required',
            'email'     => 'required|unique:users,email',
            'password'  => 'required|same:confirm_password'
        
        ]);
        
        $user->user_firstname   = $request->user_firstname;
        $user->user_lastname    = $request->user_lastname;
        $user->user_gender  = $request->user_gender;
        $user->user_phone   = $request->user_phone;
        $user->email        = $request->email;
        $user->branch_id     =\Branch::branch_id();
        $user->role          = 'Administrator';
        $user->user_activity     = 1;
        $user->user_status     = 1;
        $user->branch_id     = $request->branch_id;

        $user->password = Hash::make($request['password']);
        $user->save();
        $user->assignRole($request->input('roles'));


        // Assign Branch 
        $assign = new AssingBranchModel();
        $assign->user_id = $user->id;
        $assign->branch_id =  $request->branch_id;
        $assign->save();

        // Update Status Branch

        BranchModel::whereId($request->branch_id)->update([
            'status'=> 2
        ]);



        
        \LogActivity::addToLog('Assign user to branch successfully!');
        return redirect()->route('branches.index')
                        ->with('success','Assign user to branch successfully!');
    }
    }
}