<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use Maatwebsite\Excel\Facades\Excel;
use App\Partner;
use App\Schedule;
use App\User;
use Illuminate\Support\Facades\Validator;
use DataTables;
use Str;
use DB;
use Illuminate\Support\Facades\Auth;
use SimpleSoftwareIO\QrCode\Facades\QrCode;
use Illuminate\Support\Facades\URL;
use App\Imports\ImportSchedule;
use DateTime;
use DatePeriod;
use DateInterval;
use Log;
use PDF;

use Illuminate\Support\Facades\Hash;


class PartnerController extends Controller
{
    public function __construct()
    {
        // $this->middleware('auth');
        $this->middleware('admin');
        $this->pageTitle = 'Partner';
        // $this->masterActive = 'active';
        $this->partnerActive = 'active';
    }
    public function index()
    {
        $data = (array)$this;
        $data['form'] = [
            [ 'name' => 'name', 'label' => 'Nama', 'type' => 'text'],
            [ 'name' => 'description', 'label' => 'Deskripsi', 'type' => 'text'],
            [ 'name' => 'password', 'label' => 'Password', 'type' => 'text'],
            // ['name' => 'ket', 'label' => 'Keterangan', 'type'=>'select', 'value' => ['sa', 'tu', 'dua']]  
        ];
        $data['form_action'] = "partner.store";
        $data['form_update'] = "partner.update";
        // return json_encode($data);
        return View::make('dashboard.partner.index', $data);
    }
    public function indexData(Request $request){
        $data = Partner::where('company_id', Auth::user()->company->id);
         return Datatables::of($data)
               ->editColumn('action', function($data){ return view('dashboard.partner.index-action', compact('data'));})
               ->editColumn('anggota', function ($data) {     
                $user = User::where('partner_id', $data->id)->count();
                return $user.' orang';
                })
               ->rawColumns(['action','anggota'])
               ->make(true); 

   }

    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'description' => 'required',
            'password' => 'required',
        ]);

        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        do{
            $nama = Str::random(40);
            $cekuniq =  Partner::where('slug', $nama);
        }while(empty($cekuniq)); 

        $researche = Partner::create([
            'name' => $request->name,
            'description' => $request->description,
            'password' => Hash::make($request->password),
            'company_id' => Auth::user()->company->id,
            'slug' => $nama

            ]);

        session()->put('success','Berhasil Input.');   
        return redirect('/partner');
        
        // return json_encode($request->all());
    }

    public function destroy($id)
    {
        $data = Partner::find($id);
        if($data->count() < 1){
        session()->put('error','Gagal hapus.');
            return redirect('/partner');
        };
        $data->delete();
        session()->put('success','Berhasil Hapus.');
            return redirect('/partner');
    }
    public function look(Request $request)
    {
       
        $data = Partner::findOrFail($request->data);
        return json_encode($data);

    }
    public function update(Request $request)
    {
        // return json_encode($request->all());

        $validator = Validator::make($request->all(), [
            'name' => 'required',
        ]);
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $data = Partner::find($request->id);
        $data->name = $request->name;
        $data->description = $request->description;
        if($request->password != null){
            $data->password = Hash::make($request->password);
        };
        $data->save();
        session()->put('success','Berhasi edit!');
        return redirect('/partner');  
    }
    public function location_update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
        ]);
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $data = Partner::find($request->id);
        $data->latitude = $request->latitude;
        $data->longitude = $request->longitude;
        $data->save();
        session()->put('success','Berhasi edit!');
        return redirect('/partner/detail/'.$request->id);  
    }

    public function detail($id)
    {
        // return json_encode($id);
        $data = (array)$this;
        $partner = Partner::findOrFail($id);
        $url  = URL::to('absen/'.$partner->slug);
        $data['qr_code'] = QrCode::size(200)->generate($url);
        $data['partner'] = $partner;
        $data['member'] = User::where('partner_id', $id)->where('is_active', 1)->get();
        // $data['status'] = Status::all();
        // $data['division'] = Division::all();
        // $data['position'] = Position::all();
        // $data['partner'] = Partner::where('company_id', Auth::user()->company->id)->get();
        // $data['user'] = User::find($id);
        // $data['id'] = $id;
        // $data['file'] = File::where('user_id', $id)->get();
        // $data['history'] = History::where('user_id', $id)->get();
        // $data['contract'] = Contract::where('user_id', $id)->get();
        return View::make('dashboard.partner.detail', $data);

    }
    public function indexAjax(Request $request)
    {
  
        // $data = Schedule::get(['id', 'title as mboh', 'start', 'end']);
        // return json_encode($data);
        // Log::info('masuk'. json_encode($request->all()));
        if($request->ajax()) {
       
             $data = Schedule::where('partner_id', $request->partner_id)->whereDate('start', '>=', $request->start)
                       ->whereDate('end',   '<=', $request->end)
                    //    ->get(['id', 'title', 'start', 'end', DB::raw('CONCAT(start_plot,"-",end_plot) as description')]);
                       ->get(['id','user_id','title', 'start', 'end', 'start_plot as description','end_plot as end_time']);
                       if (!empty ($request->user_id) ){
                        $data = $data->where('user_id', $request->user_id);
                    };
  
             return response()->json($data);
        }
    }

    public function indexAjax2(Request $request)
    {
  
        // $data = Schedule::get(['id', 'title as mboh', 'start', 'end']);
        // return json_encode($data);
        // Log::info('masuk'. json_encode($request->all()));
        if($request->ajax()) {
       
             $data = Schedule::where('partner_id', $request->partner_id)->whereDate('start', '>=', $request->start)
                       ->whereDate('end',   '<=', $request->end)
                    //    ->get(['id', 'title', 'start', 'end', DB::raw('CONCAT(start_plot,"-",end_plot) as description')]);
                       ->get(['id','user_id','title', 'start', 'end', 'start_plot as description','end_plot as end_time','start_absen','end_absen']);
                       if (!empty ($request->user_id) ){
                        $data = $data->where('user_id', $request->user_id);
                    };
  
             return response()->json($data);
        }
    }
    public function ajax(Request $request)
    {
        Log::info('ajax'. json_encode($request->all()));

 
        switch ($request->type) {
           case 'add':

            $begin = new DateTime($request->start);
            $end   = new DateTime($request->end);

            $interval = DateInterval::createFromDateString('1 day');
            $period = new DatePeriod($begin, $interval, $end);

            foreach ($period as $dt) {
                // echo $dt->format("l Y-m-d H:i:s\n");
                    // echo $i->format("Y-m-d");
                    $tgl = $dt->format("Y-m-d");
                    $bsk = $dt->modify('+1 day');
                    $hari = $bsk->format("Y-m-d");
                    
                    $start = date('Y-m-d H:i:s', strtotime("$tgl $request->start_time"));
                    if(strtotime($request->start_time) > strtotime($request->end_time)){
                        $end = date('Y-m-d H:i:s', strtotime("$hari $request->end_time"));
                    }else{
                        $end = date('Y-m-d H:i:s', strtotime("$tgl $request->end_time"));
                    }
                    // $event[] = $tgl;
                    $event = Schedule::create([
                        'title' => $request->title,
                        'start' => $tgl,
                        'end' => $hari,
                        'start_plot' => $start,
                        'end_plot' => $end,
                        'user_id' => $request->user_id,
                        'partner_id' => $request->partner_id,
                    ]);
                
                // $event[] = $dt->format("Y-m-d H:i:s\n");
            }

                // for($i = $begin; $i <= $end; $i->modify('+1 day')){
                //     // echo $i->format("Y-m-d");
                //     $tgl = $i->format("Y-m-d");
                //     $bsk = $i->modify('+1 day');
                //     $hari = $bsk->format("Y-m-d");
                //     $start = date('Y-m-d H:i:s', strtotime("$tgl $request->start_time"));
                //     $end = date('Y-m-d H:i:s', strtotime("$tgl $request->end_time"));
                //     $event[] = $tgl;
                //     // $event = Schedule::create([
                //     //     'title' => $request->title,
                //     //     'start' => $tgl,
                //     //     'end' => $hari,
                //     //     'start_plot' => $start,
                //     //     'end_plot' => $end,
                //     // ]);
       
                // }

              return response()->json($event);
             break;
  
           case 'update':
              $event = Schedule::find($request->id)->update([
                  'title' => $request->title,
                  'start' => $request->start,
                  'end' => $request->end,
              ]);
 
              return response()->json($event);
             break;
  
           case 'delete':
              $event = Schedule::find($request->id)->delete();
  
              return response()->json($event);
             break;
             
           default:
             # code...
             break;
        }
    }

    public function download_berkas()
    {
    //    dd('o');

        $pathToFile = base_path().'/public/jadwal_format.xlsx';
        return response()->download($pathToFile);

    }


    public function import_schedule(Request $request){

        // return json_encode($request->all());
        $validator = Validator::make($request->all(), [
            'user_id' => 'required',
        ]);
        if ($validator->fails()) {
            session()->put('error','export gagal.');
            return back();
        }

        try{

        foreach ($request->user_id as $item){ 
            // Code Here
            
            $data['user_id']=$item;
            // $data['user_id']=$request->user_id;
            $data['partner_id']=$request->partner_id;

            Excel::import(new ImportSchedule($data), request()->file('file'));
        }
            session()->put('success','Berhasi upload!');
            return redirect()->back();
        }catch (\Exception $e) {
            session()->put('error','Gagal upload!');
            return redirect()->back();
        }
    }

    public function look_schedule(Request $request){

        // return json_encode($request->all());
        $data = Schedule::findOrFail($request->id);
        return $data;
       
    }
    public function sub_schedule(Request $request){

        // return json_encode($request->all());
        $date = explode(' - ', $request->tanggal);
        $start = $date[0];
        $end = $date[1];

        $data = Schedule::find($request->id);
        $data->start_absen =  date('Y-m-d H:i:s', strtotime($start));
        $data->end_absen = date('Y-m-d H:i:s', strtotime($end));
        $data->save();
        // $data = Schedule::findOrFail($request->id);
        return json_encode('success');
       
    }

    public function batal_pulang(Request $request){

        // return json_encode($request->all());
            $data = Schedule::find($request->id);
        $data->end_absen = null;
        $data->save();
        // $data = Schedule::findOrFail($request->id);
        return json_encode('success');
       
    }
    public function cetak_qr($id){

        // $data['id'] = $id;
        // $data['salary'] = Salary::with('user:name,id', )findOrFail($id);
     //    $ss = Salary::findOrFail($id);
 
     $partner = Partner::findOrFail($id);
     $url  = URL::to('absen/'.$partner->slug);
        $data['qr_code'] = QrCode::size(400)->generate($url);
        $data['partner'] = $partner;
      
        $data['company'] = strtoupper(Auth::user()->company->name);
        $data['admin'] = 'Irawan Pramudhita, SE';
 
 
        // return json_encode($data);
     $pdf = PDF::loadView('dashboard.partner.cetak-prev', $data)->setPaper('a4', 'potrait');
         return $pdf->stream('cetak.pdf');
        //  return $pdf->download('cetak.pdf');
 
    }

}