<?php

namespace App\Http\Controllers\Administrator;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\ProjectModel;
use App\ProvinceModel;
use DataTables;
use DB;
use App\DistrictModel;
use App\CommuneModel;
use App\VillageModel;
use Illuminate\Support\Facades\Crypt;
use App\Events\Notify;
use App\Fun\Fun;
use App\BranchModel;
use Image;
use Gate;
class ProjectController extends Controller
{
    function __construct()
    {
        $this->middleware('permission:Project-List');
        $this->middleware('permission:Project-Create', ['only' => ['create','store']]);
        $this->middleware('permission:Project-Edit', ['only' => ['edit','update']]);
        $this->middleware('permission:Project-Delete', ['only' => ['destroy']]);
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request){
       return view('administrator.projects.index');
    }

    public function datatable_get_projects(Request $request)
    {
        $project_code = $request->code;
        $project_name = $request->project_name ;
        $project = ProjectModel::with(['get_province','get_district','get_commune','get_village'])
            ->when(empty(\Branch::branch_key()), function ($query) {
                $query->where('nso007_project_stock.branch_id', \Branch::branch_id());
            })
            ->when(request('code'),function($query) use ($project_code){
                $query->where("nso007_project_stock.project_code",$project_code);
            })
            ->when(request('project_name'),function($query) use ($project_name){
                $query->where("nso007_project_stock.project_name","LIKE","%".$project_name."%");
            })
            ->get();
        return  Datatables::of($project)
            ->addIndexColumn()
            ->addColumn('action', function($project) {
                $btn_delete='';
                $btn_edit = "";
                if (Gate::check('Project-Edit'))
                    $btn_edit = '<a href="' . Route("projects.edit", Crypt::encrypt($project->id)) . '" class="button_success fa fa-edit" data-toggle="tooltip" data-placement="top" title="Edit"></a>';

                if ($project->status == 1)
                    if (Gate::check('Project-Delete'))
                        $btn_delete .= ' <a href="#" data-id = "' . $project->id . '" data-toggle="modal" data-target="#form-delete" class="button_danger fa fa-trash confirm_delete" data-toggle="tooltip" data-placement="top" title="Delete"></a>';
                return $btn_edit.$btn_delete;
            })
            ->editColumn('feature',function($project){
                $img = $project->feature!='none' ? asset('assets/images/resize/768x768/'.$project->feature):asset('assets/images/default.png');
                return '<img src="'.$img.'" alt="Loading" style="width:40px">';
            })
            ->editColumn('address', function($project) {
                return  optional(VillageModel::find($project->p_village))->address($project->house_number,$project->street_number);
            })
            ->addColumn('project_type', function($project) {
                
                if($project->type == 1){
                    return 'Internal';
                }else{
                    return 'External';
                }
            })
            ->editColumn('project_des', function($project) {
                $project_des = substr($project->project_des, 0, 50);
                return  $project_des."...";
            })
            ->editColumn('commission_amount', function($project) {
                if ($project->type == 1) {
                    $commission_amount = "N/A";
                } else {
                    $commission_amount = number_format($project->commission_amount, 2)." $";
                }
                return  $commission_amount;
            })
            ->editColumn('commission', function($project) {
                if ($project->type == 1) {
                    $commission = "N/A";
                } else {
                    $commission = number_format($project->commission, 2)." %";
                }
                return  $commission;
            })
            ->editColumn('condition', function($project) {
                if ($project->type == 1) {
                    $condition = "N/A";
                } else {
                    $condition = number_format($project->condition, 2)." %";
                }
                return  $condition;
            })
            ->rawColumns(['feature'=>'feature'])
            ->make(true);
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        $provinces = ProvinceModel::select(
            DB::raw('CONCAT(province_id," ",province_en," ",province_km) AS province_mixed'),'province_id')
            ->pluck('province_mixed','province_id')
            ->prepend('Please Select', '');
        $branches = BranchModel::when(empty(\Branch::branch_key()), function ($query) {
            $query->where('nso007_branches.id', \Branch::branch_id());
            })
            ->select(
            DB::raw('CONCAT(id," ",branch_en," ",branch_kh) AS branch_name'),'id')
            ->pluck('branch_name','id');
        return view('administrator.projects.create',compact('provinces','branches'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
         $rules = [
            'project_code'      => 'required',
            'project_name'      => 'required',
            'project_type'      => 'required',
            'p_province'    => 'required',
            'p_district'    => 'required',
            'p_commune'     => 'required',
            'p_village'     => 'required',
            'branch_id'     => 'required',
        
        ];

        if ($request->project_type == 2) {
            
        }
        $customMessages = [
        ];


        $this->validate($request, $rules, $customMessages);



         $file       = $request->file('project_logo');
         if($request->file('project_logo')== null){
             $original_name = "none";
         }else{
             $original_name = $file->getClientOriginalName();
             $original_name = date('ymdhis').$original_name;
             $destinationPath = 'assets/images/resize/180x80';
             $thum = Image::make($file->getRealPath())->resize(180, 80);
             $thum->save($destinationPath.'/'.$original_name,80);
         }

        $project_feature       = $request->file('project_feature');
        if($request->file('project_feature')== null){
            $original_name1 = "none";
        }else{
            $original_name1 = $project_feature->getClientOriginalName();
            $original_name1 = date('ymdhis').$original_name1;
            $destinationPath = 'assets/images/resize/768x768';
            $thum = Image::make($project_feature->getRealPath())->resize(768, 768);
            $thum->save($destinationPath.'/'.$original_name1,80);
        }

        $project = new ProjectModel;
        $project->branch_id     = $request->branch_id;
        $project->project_code  = $request->project_code;
        $project->project_name  = $request->project_name;
        $project->project_des   = $request->project_des;
        $project->type          = $request->project_type;
        $project->commission_amount=$request->commission_amount;
        $project->commission    = $request->commission;
        $project->condition     = $request->condition;
        $project->project_phone = $request->project_phone;
        // $project->logo          = $original_name;
        $project->feature       = $original_name1;
        $project->p_village     = $request->p_village;
        $project->p_commune     = $request->p_commune;
        $project->p_district    = $request->p_district;
        $project->p_province    = $request->p_province;
        $project->house_number  = $request->house_number;
        $project->street_number = $request->street_number;
        $project->save();
        \LogActivity::addToLog('Project created successfully ! ');
        return redirect()->route('projects.index')
        ->with('success','Project created successfully !');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $decrypt_id = Crypt::decrypt($id);
        $project = ProjectModel::find($decrypt_id);
        $provinces = ProvinceModel::select(
            DB::raw('CONCAT(province_id," ",province_en," ",province_km) AS province_mixed'),'province_id')
            ->pluck('province_mixed','province_id')
            ->prepend('Please Select', '');
        $districts = DistrictModel::select(
        DB::raw('CONCAT(district_id," ",district_en," ",district_km) AS district_mixed'),'district_id')
        ->pluck('district_mixed','district_id')
        ->prepend('Please Select', '');
       
        $communes = CommuneModel::select(
            DB::raw('CONCAT(commune_id," ",commune_en," ",commune_km) AS commune_mixed'),'commune_id')
            ->pluck('commune_mixed','commune_id')
            ->prepend('Please Select', '');
        $villages = VillageModel::select(
            DB::raw('CONCAT(village_id," ",village_en," ",village_km) AS village_mixed'),'village_id')->where("village_id",$project->p_village)
            ->pluck('village_mixed','village_id')
            ->prepend('Please Select', '');

        $branches = BranchModel::select(
            DB::raw('CONCAT(id," ",branch_en," ",branch_kh) AS branch_name'),'id')
            ->pluck('branch_name','id')
            ->prepend('Please Select', '');

        return view('administrator.projects.edit',compact('project', 'provinces','districts','communes','villages','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)
    {
        $project = ProjectModel::find($id);
        $rules = [
            'project_code'      => 'required',
            'project_name'      => 'required',
            'project_type'      => 'required',
            'p_province'    => 'required',
            'p_district'    => 'required',
            'p_commune'     => 'required',
            'p_village'     => 'required',
            'branch_id'     => 'required',
            // 'house_number'  => 'required',
            // 'street_number' => 'required',
//            'project_feature'     => 'dimensions:height=768,width=768',
            // 'project_logo'     => 'dimensions:height=80,width=180', 
        
        ];
        if ($request->project_type == 2) {
            // if($request->commission_amount){
            //     $this->validate($request,[
            //         'commission_amount' => 'required|numeric' 
            //     ]);
            // }else{
            //     $this->validate($request, [
            //         'commission'      => 'required|numeric',
            //         'condition'      => 'required|numeric',        
            //     ]);
            // }
        }
        $customMessages = [
//            'project_feature.height.width' => 'Maximum width and height to upload is 768x768 pixcel',
            // 'project_logo.height.width' => 'Maximum width and height to upload is 80x180 pixcel'
        ];

        $this->validate($request, $rules, $customMessages);
        
//         $project_logo_old = $request->project_logo_old;
//         $file       = $request->file('project_logo');
//         if($request->file('project_logo')== null){
//             $original_name = $project_logo_old;
//         }else{
//             $original_name = $file->getClientOriginalName();
//             $original_name = date('ymdhis').$original_name;
//             if(file_exists(public_path().'/assets/images/resize/180x80'.$project_logo_old)){
//                 unlink(public_path().'/assets/images/resize/180x80'.$project_logo_old);
//             }
//             $destinationPath = 'assets/images/resize/180x80';
//             $thum = Image::make($file->getRealPath())->resize(180, 80);
//             $thum->save($destinationPath.'/'.$original_name,80);
//         }

        $project_feature_old = $request->project_feature_old;
        $project_feature     = $request->file('project_feature');
        if($request->file('project_feature')== null){
            $original_name1 = $project_feature_old;
        }else{
            $original_name1 = $project_feature->getClientOriginalName();
            $original_name1 = date('ymdhis').$original_name1;
            if(file_exists(public_path().'/assets/images/resize/768x768'.$project_feature_old)){
                unlink(public_path().'/assets/images/resize/768x768'.$project_feature_old);
            }
            $destinationPath = 'assets/images/resize/768x768';
            $thum = Image::make($project_feature->getRealPath())->resize(768, 768);
            $thum->save($destinationPath.'/'.$original_name1,80);
        }

        $project->branch_id     = $request->branch_id;
        $project->project_code = $request->project_code;
        $project->project_name = $request->project_name;
        $project->type = $request->project_type;
        // $project->commission_amount=$request->commission_amount;
        // $project->commission    = $request->commission;
        // $project->condition     = $request->condition;
        $project->project_des = $request->project_des;
        // $project->logo          = $original_name;
        $project->feature       = $original_name1;
        $project->p_village = $request->p_village;
        $project->p_commune = $request->p_commune;
        $project->p_district = $request->p_district;
        $project->p_province = $request->p_province;
        $project->project_phone = $request->project_phone;
        $project->house_number  = $request->house_number;
        $project->street_number = $request->street_number;
        $project->update();
        \LogActivity::addToLog('Project updated successfully !');
        return redirect()->route('projects.index')
        ->with('success','Project updated successfully!');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request)
    {
        $delete_project = ProjectModel::find($request->delete_id);
        $delete_project->delete();
        \LogActivity::addToLog('Delete Project successfully');
        return response()->json(['success' => true, 'message' => 'Delete Project successfully']);
    }
}
