<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\CustomExport;
use App\Imports\ImportEmployee;
use App\Helpers\Helper;
use App\Mail\ArtSend;
use App\Models\Employee;
use App\Models\Lead;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Mail;
use Yajra\DataTables\Facades\DataTables;
use Illuminate\Support\Facades\Validator;

use Illuminate\Support\Facades\Artisan;

class LeadController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //dd('ok');
        return view('Admin.lead.index', ['data' => array()]);
    }

    public function findData(Request $request)
    {
        $data = array();
        $input = $request->input();
        if(count($input) > 0){
            $data = $input;
            $data['show_table'] = 1;
            session()->flashInput($request->input());
        }
        return view('Admin.lead.index', ['data' => array()]);
    }

    public function create()
    {
        return redirect()->back();
        //return view('Admin.lead.create_edit');
    }

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

    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        return redirect()->back();
        // $data = Employee::find(decrypt($id));
        // //dd($data);
        // return view('Admin.lead.create_edit', ['data' => $data]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        return redirect()->back();
        // //dd($request);
        // $validator = Validator::make($request->all(), [
        //     'employee_id' => 'required|unique:employees,id,'.$id,
        //     'employee_name' => 'required',
        //     'email' => 'required|email|unique:employees,id,'.$id,
        //     'profile_image' => 'mimes:jpeg,jpg,png',
        //     'whatsapp_number' => 'required|numeric|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
        //     'mobile_number' => 'numeric|regex:/^([0-9\s\-\+\(\)]*)$/|min:10',
            
        // ]);
        // if ($validator->fails()) {
        //     return redirect()->back()->withErrors($validator)->withInput();
        // }
        // $input = $request->input();
        // unset($input['_token']);
        // unset($input['_method']);
        // $Employee = Employee::find($id);
        // if($request->hasfile('profile_image'))
        // {
        //     $destinationPath = public_path('/images/employee/');
        //     if(!empty($Employee->profile_image) && file_exists($destinationPath.$Employee->profile_image)){
        //         File::delete($destinationPath.$Employee->profile_image);
        //     }
        //     $image = $request->profile_image;
        //     $fileName = "AG-EMP".rand(10,99).date('dmyhisa') . '.' . $image->extension();
        //     $fileName = str_replace(" ", "-", $fileName);
            
            
        //     if (!is_dir($destinationPath)) {
        //         mkdir($destinationPath, 0777, TRUE);
        //         @chmod($destinationPath,0777);
        //     }
        //     $image->move($destinationPath, $fileName);
        //     $input['profile_image'] = $fileName;
        // }
        // Lead::where("id", $id)->update($input);
        // Helper::successMsg("update", "Employee");
        // return redirect()->route('lead.index');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Lead::where("id",decrypt($id))->delete();
        Helper::successMsg("delete", "Lead");
        return redirect()->back();
    }
    public function delete($id)
    {
        Lead::where("id",decrypt($id))->delete();
        Helper::successMsg("delete", "Lead");
        return redirect()->back();
    }
    public function status(Request $request, $id)
    {
        Lead::where("id",decrypt($id))->update(array("status"=>$request->status,"updated_at"=>date("Y-m-d H:i:s")));
        Helper::successMsg("Status", "Lead");
        return redirect()->back();
    }

    public function data(Request $request)
    {
        $where = array();
        //filters
        if($request->filters != ""){
            foreach($request->filters as $k=>$v){
                (($v['name'] == 'name') && $v['value'] != "")?($where[] = ["customer","LIKE", "%".$v['value']."%"]):"";
            }
        }

        if(empty($where)){
            $where = array(["id", ">", 0]);
        }
        session(["whereExportFilter" => ['whereExport' => $where]]);
        // dd($where);
        $start = $request->has('start')?(int)$request->start:0;
        $perPage = $request->has('length')?(int)$request->length:10;

        $totalRecord = Lead::where($where)->count();
        $tableData = Lead::with('employeeName')->where($where)->orderBy('id', 'asc')->offset($start)->limit($perPage)->get();
        //dd($tableData);
        $datatable = DataTables::of($tableData)
            ->skipPaging()
            ->setTotalRecords($totalRecord)
            ->editColumn('selectbox', function ($val) {
                return '<input type="checkbox" name="checkedboxes[]" value="'.$val->id.'"/>';
            })
            ->addIndexColumn()
            ->addColumn('employee_id', function ($val) {
                if(!empty($val->employeeName)){
                    return $val->employeeName->employee_id;
                }
            })
            ->addColumn('employee_name', function ($val) {
                if(!empty($val->employeeName->employee_name)){
                    return $val->employeeName->employee_name;
                }
            })
            ->addColumn('upload_art', function ($val) {
                
                $upload_art = "";
                
                $upload_art .= '<input type="file" id="artUpload" name="upload" onchange="artUploading(this, `'.route('lead.uploadArt', $val->id).'`)" class="form-control artUpload" value="" data-art_id="'.$val->id.'" accept="image/jpeg,image/gif,image/png,application/pdf,image/x-eps"/>';
                
                if(!empty($val->upload)){
                    //disable
                    $upload_art .= '<a href="'.asset('images/art/'.$val->upload).'"download style="" class="btn btn-sm btn-danger btn-link text-light" rel="tooltip" data-placement="bottom" title="Art DownLoads">Art Downloads</a>';
                }
                return $upload_art;
            })
            
            ->addColumn('status', function ($val) {
                $encrypt = encrypt($val->id);
                $status = "";
                
                if($val->status == "0"){
                    //disable
                    $status .= '<button type="button" style="" class="btn btn-sm status_btn btn-danger btn-link" data-next_click="1" data-status_link="' . route('lead.status', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Deactive"><i class="fas fa-times" aria-hidden="true"></i></button>';
                }else{
                    $status .= '<button type="button" style="" class="btn btn-sm status_btn btn-success btn-link" data-next_click="0" data-status_link="' . route('lead.status', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Active"><i class="fas fa-check" aria-hidden="true"></i></button>';
                }
                return $status;
            })
            ->addColumn('action', function ($val) {
                $encrypt = encrypt($val->id);
                $action = "";
                
                //$action .= '<a class="bt.n btn-sm btn-primary btn-link" href="' . route('lead.edit', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Edit"><i class="fas fa-pen" aria-hidden="true"></i></a>';
                $action .= '<button type="button" style="" class="btn btn-sm delete_btn btn-danger btn-link" data-delete_link="' . route('lead.delete', $encrypt) . '" rel="tooltip" data-placement="bottom" title="Delete"><i class="fas fa-trash" aria-hidden="true"></i></button>';
                
                return $action;
            })
            ->rawColumns(['selectbox','employee_id', 'employee_name', 'upload_art','status','action'])
            ->make(true);
        return $datatable;
    }

    public function export(Request $request)
    {
        $where = array(["id", ">", 0]);
        
        if(session()->has('whereExportFilter')){
            $where = session()->get('whereExportFilter')['whereExport'];
        }
        $data = Lead::with('employeeName')->where($where)->orderBy('id', 'desc')->get();
        return Excel::download(new CustomExport("Admin.lead.export", ["data"=>$data, "title"=>"Employees Leads"]),  'employees_leads.xlsx');
    }
    public function multiDelete(Request $request){
        $Event = $request->has('checkedboxes')?$request->checkedboxes:array();
        if(count($Event) > 0){
            Lead::whereIn("id", $Event)->delete();
            Helper::successMsg("delete", "Leads");
        }else{
            Helper::failarMsg("custom", "Not Allowed to delete Multi records!");
        }
        return redirect()->back();
    }
    public function uploadArt(Request $request, $id)
    {
        //dd($request);
        //return true;
        $art = Lead::where('id', $id)->first();
        if($request->hasfile('pictureFile'))
        {
            $destinationPath = public_path('/images/art/');
            if(!empty($art->upload) && file_exists($destinationPath.$art->upload)){
                File::delete($destinationPath.$art->upload);
            }
            $image = $request->pictureFile;
            $fileName = "AG-ART".rand(10,99).date('dmyhisa') . '.' . $image->extension();
            $fileName = str_replace(" ", "-", $fileName);
            
            
            if (!is_dir($destinationPath)) {
                mkdir($destinationPath, 0777, TRUE);
                @chmod($destinationPath,0777);
            }
            $image->move($destinationPath, $fileName);
            $art = $fileName;
        }
        Lead::where('id', $id)->update(['upload' => $art ]);

        $lead = Lead::where('id', $id)->first();
        $employee = Employee::where("id", $lead->employee_id)->first();
        $message = "Please find the attached art creative for ".$lead->customer;
        $filename = public_path('/images/art/').$art;
        $data = array(
            "employee" => $employee,
            "lead"  =>  $lead,
            "filename"  =>  $filename,
            "message" => $message
        );
        Mail::to($employee->email)->queue(new ArtSend($data));
        $run = Artisan::call('queue:work --stop-when-empty');

        // Helper::failarMsg("custom", "AG Art uploaded successfully!");
        return response()->json(["status"=>1,"message"=>"AG Art uploaded successfully!","items"=>$data]);
    
    }
    
    
}