<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use App\Group;
use App\Question;
use App\Division;
use App\Master;
use App\Answer;
use App\Partner;
use Illuminate\Support\Facades\Validator;
use DataTables,PDF;
use Illuminate\Support\Facades\Auth;
use Carbon\Carbon;
use App\For_signature;
use Illuminate\Support\Facades\Log;




class CeklistController extends Controller
{
    public function __construct()
    {
        // $this->middleware('auth');
        $this->middleware('admin');
        $this->ceklistActive = 'active';
    }
    public function index()
    {
        $this->dataActive = 'active';
        $this->pageTitle = 'Ceklist';
        $data = (array)$this;
        $division = Division::all();

        $data['form'] = [
            [ 'name' => 'title', 'label' => 'Nama', 'type' => 'text'],
            // [ 'name' => 'description', 'label' => 'Deskripsi', 'type' => 'text'],
            ['name' => 'division_id', 'label' => 'Divisi', 'type'=>'select', 'option' =>$division],

            ['name' => 'is_active', 'label' => 'Status', 'type'=>'select', 'option' => [
                ['id'=>1, 'name'=>'Aktif'],
                ['id'=>0, 'name'=>'Non-Aktif']
                ]  
            ]
        ];
        $data['form_action'] = "ceklist.store";
        $data['form_update'] = "ceklist.update";
        $data['form_delete'] = "ceklist.destroyQuestion";

        // return json_encode($data);
        return View::make('dashboard.ceklist.index', $data);
    }
    public function indexData(Request $request){
        $data = Group::with('division');
         return Datatables::of($data)
               ->editColumn('action', function($data){ return view('dashboard.ceklist.index-action', compact('data'));})
               ->editColumn('title', function ($data) { 
                
                    if($data->is_active == 1){
                        return "<a class='btn btn-primary' href='".route('ceklist.detail', $data->id)."' >"
                                .$data->title.
                            "</a>";
                        }else{
                            return "<a class='btn btn-default' href='#' >"
                            .$data->title.
                            "</a>";
                        }
                })
               ->rawColumns(['action','title'])
               ->make(true); 

   }

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

        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $researche = Group::create([
            'title' => $request->title,
            'is_active' => $request->is_active,
            'division_id' => $request->division_id,
            'company_id' => Auth::user()->company->id
            ]);

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

    public function destroy($id)
    {
        $data = Group::find($id);
        if($data->count() < 1){
        session()->put('error','Gagal hapus.');
        return back();
        };
        $data->delete();
        session()->put('success','Berhasil Hapus.');
        return back();

    }
    public function look(Request $request)
    {
       
        $data = Group::findOrFail($request->data);
        return json_encode($data);

    }
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required',
        ]);
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $data = Group::find($request->id);
        $data->title = $request->title;
        $data->is_active = $request->is_active;
        $data->division_id = $request->division_id;
        $data->save();
        session()->put('success','Berhasi edit!'); 
        return back();

    }
    public function detail($id)
    {
        $this->dataActive = 'active';
        $question = Group::findOrFail($id);
        $this->pageTitle = 'Detail Ceklist : '.$question->title;
        $data = (array)$this;
        $data['form'] = [
            [ 'name' => 'title', 'label' => 'Pertanyaan', 'type' => 'text'],
            [ 'name' => 'group_id', 'label' => 'group_id', 'type' => 'hidden', 'value' => $id],
            // ['name' => 'type', 'label' => 'Tipe', 'type'=>'select', 'option' => [
            //     ['id'=>'uraian', 'name'=>'Uraian'],
            //     ['id'=>'pilihan ganda', 'name'=>'Pilihan Ganda']
            //     ]  
            // ],
            // [ 'name' => 'option', 'label' => 'Pilihan', 'type' => 'tag']
        ];
        $data['form_action'] = "ceklist.storeQuestion";
        $data['form_update'] = "ceklist.updateQuestion";
        // $data['form_delete'] = "ceklist.destroyQuestion";
        $data['group_id'] = $id;

        // return json_encode($data);
        return View::make('dashboard.ceklist.detail', $data);
    }
    public function dataQuestion(Request $request){
        $data = Question::all();
        if (!empty ($request->get('group_id')) ){
            $data = $data->where('group_id', $request->get('group_id'));
        };
         return Datatables::of($data)
               ->editColumn('action', function($data){ return view('dashboard.ceklist.detail-action', compact('data'));})
               ->editColumn('title', function ($data) { 
                if($data->option){
                    return $data->title.'option :{'.$data->option.'}';
                }else{
                    return $data->title;
                }
            })
               ->rawColumns(['action', 'title'])
               ->make(true); 

   }

   public function storeQuestion(Request $request)
    {
        // return json_encode($request->all());
        $validator = Validator::make($request->all(), [
            'title' => 'required',
            // 'type' => 'required',
        ]);

        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $researche = Question::create([
            'title' => $request->title,
            // 'type' => $request->type,
            'group_id' => $request->group_id,
            // 'option' => $request->option ?? null
            ]);

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

    public function destroyQuestion($id)
    {
        $data = Question::find($id);
        if($data->count() < 1){
        session()->put('error','Gagal hapus.');
        return back();
        };
        $data->delete();
        session()->put('success','Berhasil Hapus.');
        return back();

    }
    public function lookQuestion(Request $request)
    {
       
        $data = Question::findOrFail($request->data);
        return json_encode($data);

    }
    public function updateQuestion(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'title' => 'required',
        ]);
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $data = Question::find($request->id);
        $data->title = $request->title;
        // $data->type = $request->type;
        // $data->option = $request->option ?? null;
        $data->save();
        session()->put('success','Berhasi edit!'); 
        return back();

    }
    public function lihat($id)
    {
        // return json_encode($id);
        $this->dataActive = 'active';
        $question = Group::findOrFail($id);
        $this->pageTitle = 'Preview Ceklist : '.$question->title;
        $data = (array)$this;
        // $data['form'] = [
        //     [ 'name' => 'title', 'label' => 'Pertanyaan', 'type' => 'text'],
        //     [ 'name' => 'group_id', 'label' => 'group_id', 'type' => 'hidden', 'value' => $id],
        //     ['name' => 'type', 'label' => 'Tipe', 'type'=>'select', 'option' => [
        //         ['id'=>'uraian', 'name'=>'Uraian'],
        //         ['id'=>'pilihan ganda', 'name'=>'Pilihan Ganda']
        //         ]  
        //     ],
        //     [ 'name' => 'option', 'label' => 'Pilihan', 'type' => 'tag']
        // ];
        // $data['form_action'] = "ceklist.storeQuestion";
        // $data['form_update'] = "ceklist.updateQuestion";
        // // $data['form_delete'] = "ceklist.destroyQuestion";
        $data['question'] = Question::where('group_id', $id)->get();

        $data['group_id'] = $id;

        // return json_encode($data);
        return View::make('dashboard.ceklist.lihat', $data);
    }

    public function rekap()
    {
        $this->rekapActive = 'active';
        $this->pageTitle = 'Rekap';
        $data = (array)$this;
        $division = Division::all();
        $data['group'] = Group::all();
        $data['partner'] = Partner::where('company_id', Auth::user()->company->id)->get();

       

        // return json_encode($data);
        return View::make('dashboard.ceklist.rekap', $data);

    }

    public function rekapData(Request $request){
        $data = Master::with('user:name,id', 'partner:id,name,company_id', 'group.question' )->whereHas('partner', function ($query) {
            $query->where('company_id', Auth::user()->company->id);
            });
        if (!empty ($request->get('group_id')) ){
            $data = $data->where('group_id', $request->get('group_id'));
        };
        if (!empty ($request->get('partner_id')) ){
            $data = $data->where('partner_id', $request->get('partner_id'));
        };

        if (!empty ($request->get('date')) ){
            Log::info(json_encode($request->get('date')));
            $date = explode(' - ', $request->get('date'));
            $start = $date[0];
            $end = $date[1];
            $data = $data->whereBetween('created_at', [$start, $end]);
            // ->whereBetween('created_at', [$start, $end])
        };

         return Datatables::of($data)
         ->editColumn('action', function($data){ return view('dashboard.ceklist.rekap-action', compact('data'));})

               ->rawColumns(['action'])
               ->make(true); 
            }


    public function cetak_pdf_ceklist($id){

                // $data['id'] = $id;
                // $data['salary'] = Salary::with('user:name,id', )findOrFail($id);
                $master = Master::with('user:name,id', 'partner:id,name', 'group.question', 'group.division' )->findOrFail($id);
                $data['master'] = $master;
                // return json_encode($master->group->division->name);
                $data['answer'] = Answer::where('master_id', $master->id)->get();
                // $data['uraian'] = json_decode($data['salary']['uraian']);
                $data['company'] = strtoupper(Auth::user()->company->name);
                $data['user'] = strtoupper(Auth::user()->name);
                $data['admin'] = 'Irawan Pramudhita, SE';
                // Satuan Pengaman (Satpam)
                if($master->group->division->name == "Satuan Pengaman (Satpam)"){

                    $data['signature'] = For_signature::with('signature')->where('name', 'Cek List Security')->first();
                }else if($master->group->division->name == "Cleaning Service"){
                    $data['signature'] = For_signature::with('signature')->where('name', 'Cek List CS')->first();

                }else{
                    $data['signature'] = "";
                }

            
            
                $pdf = PDF::loadView('dashboard.record.cetak', $data)->setPaper('a4', 'potrait');
                    return $pdf->stream('ceklist_harian.pdf');
                    // return $pdf->download('ceklist_harian.pdf');
            
               }


    public function generateRekap(Request $request){
        try{
        $date = explode(' - ', $request->date_range);
        $start = $date[0];
        $end = $date[1];
        // return json_encode($start);

        $master = Master::with('user:name,id', 'partner:id,name', 'group.question','answer' )
                            ->where('group_id', $request->group_id)
                            ->where('partner_id', $request->partner_id)
                            // ->whereDate('created_at', '>=', $start)
                            // ->whereDate('created_at', '<=', $end)
                            ->whereBetween('created_at', [$start, $end])
                            ->get();
        $data['master'] = $master;
        // $data['answer'] = Answer::where('master_id', $master->id)->get();
        $data['group'] = Group::with('question')->where('id', $request->group_id)->first();
        $data['partner'] = Partner::where('id', $request->partner_id)->first();
        $data['date'] = $request->date_range;
        // return json_encode($data);
        // $data['uraian'] = json_decode($data['salary']['uraian']);
        $data['company'] = strtoupper(Auth::user()->company->name);
        $data['user'] = strtoupper(Auth::user()->name);
        $data['admin'] = 'Irawan Pramudhita, SE';
    
    
        $pdf = PDF::loadView('dashboard.ceklist.cetak-generate', $data)->setPaper('a4', 'landscape');
            return $pdf->stream('generate.pdf');
            // return $pdf->download('generate.pdf');

        }catch (\Exception $e) {
            session()->put('error','Gagal generate!');
            return redirect()->back();
        }
    }

   
}