<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Period;
use Illuminate\Support\Facades\View;
use App\User;
use App\Partner;
use App\Role;
use App\Salary;
use App\Variable;
use App\Component;
use App\Detail;
use App\For_signature;

use DataTables;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use App\Schedule;
use PDF;
use Illuminate\Support\Facades\Log;







class PenggajianController extends Controller
{
    public function __construct()
    {
        // $this->middleware('auth');
        $this->middleware('admin');
        $this->penggajianActive = 'active';
    }
    public function index()
    {
        $this->pageTitle = 'Setting Penggajian';
        $this->penggajianSetActive = 'active';
        $data = (array)$this;
        $data['partner'] = Partner::all();
        $data['variable_penambah'] = Variable::where('description', 'Penambah')->get();
        $data['variable_pengurang'] = Variable::where('description', 'Pengurang')->get();
        // $data['form'] = [
        //     [ 'name' => 'name', 'label' => 'Nama', 'type' => 'text'],
        //     [ 'name' => 'description', 'label' => 'Deskripsi', '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.penggajian.index', $data);
    }

    public function indexData(Request $request){
        $us = Role::where('name', 'Member')->get();
        $data = User::with('role','company','partner')->where('role_id', $us[0]->id)->where('company_id', Auth::user()->company->id,);
        if (!empty ($request->get('partner_id')) ){
            $data = $data->where('partner_id', $request->get('partner_id'));
        };
         return Datatables::of($data)
               ->editColumn('action', function($data){ return view('dashboard.penggajian.action-setting', compact('data'));})
               ->rawColumns(['action'])
               ->make(true); 

   }

   public function look_gaji(Request $request)
    {
       
        $data = User::findOrFail($request->data);
        return json_encode($data);

    }
    public function look_salary(Request $request)
    {
       
        // $data = User::findOrFail($request->data);
        $data = Salary::findOrFail($request->data);
        // $kirim = json_decode($data['uraian']);
        return json_encode($data);

    }
    public function update_gaji(Request $request)
    {
        // return json_encode($request->all());
        try{
        $data = User::find($request->id);
        $data->gaji_pokok = $request->gaji_pokok ?? null;
        $data->tunjangan_jabatan = $request->tunjangan_jabatan ?? null;
        $data->potongan_bpjs_kesehatan = $request->potongan_bpjs_kesehatan ?? null;
        $data->potongan_bpjs_ketenagakerjaan = $request->potongan_bpjs_ketenagakerjaan ?? null;
        $data->potongan_payroll = $request->potongan_payroll ?? null;
        $data->save();
        return json_encode('success');
         }catch (\Exception $e) {
            return json_encode('failed');
        }
       
    }
    public function generate()
    {
        $this->pageTitle = 'Generate Penggajian';
        $this->penggajianGenerateActive = 'active';
        $data = (array)$this;
        $data['partner'] = Partner::all();
        $data['form'] = [
            [ 'name' => 'start', 'label' => 'Tanggal Mulai', 'type' => 'date'],
            [ 'name' => 'end', 'label' => 'Tanggal Akhir', 'type' => 'date'],
            // ['name' => 'ket', 'label' => 'Keterangan', 'type'=>'select', 'value' => ['sa', 'tu', 'dua']]  
        ];
        $data['form_action'] = "penggajian.store";
        $data['form_update'] = "penggajian.update_gaji";
        // return json_encode($data);
        return View::make('dashboard.penggajian.generate', $data);
    }
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'start' => 'required',
            'end' => 'required',
        ]);

        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        

        $researche = Period::create([
            'start' => $request->start,
            'end' => $request->end,
            'company_id' => Auth::user()->company->id
            ]);

        session()->put('success','Berhasil Input.');   
        return redirect('/penggajian/generate');
        
        // return json_encode($request->all());
    }
    public function dataPeriod(Request $request){
        
        $data = Period::where('company_id', Auth::user()->company->id);
         return Datatables::of($data)
               ->editColumn('action', function($data){ return view('dashboard.penggajian.action-generate', compact('data'));})
               ->editColumn('start', function ($data) {     
                return "<a class='btn btn-primary' href='".route('penggajian.detail', $data->id)."' >"
                        .date('d F Y', strtotime($data->start))." - ".date('d F Y', strtotime($data->end)).
                    "</a>";
                    // return date('d F Y', strtotime($data->start)).' - '. date('d F Y', strtotime($data->end));
                    })
                
               ->rawColumns(['action','start'])
               ->make(true); 

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

        };
        $data->delete();
        session()->put('success','Berhasil Hapus.');
        return back();
            
    }
    public function detail($id)
    {
        // return json_encode($id);
        // $this->pageTitle = 'Detail Penggajian';

        // $salary = Salary::with('user')->get();
        // return json_encode($salary);
        $this->penggajianGenerateActive = 'active';
        $period = Period::findOrFail($id);
        $this->pageTitle = 'Detail Penggajian peroide '.date('d F Y', strtotime($period->start)).' - '.date('d F Y', strtotime($period->end));
        $data = (array)$this;
        // $partner = Partner::findOrFail($id);
        $data['partner'] = Partner::where('company_id', Auth::user()->company->id)->get();
        $data['period_id'] = $period->id;
        $user = User::where('is_payroll', '!=', 1)->orWhere('is_payroll', null)->get();
        // return json_encode($user);
        $data['form'] = [
            // [ 'name' => 'name', 'label' => 'Nama', 'type' => 'text'],
            ['name' => 'user_id', 'label' => 'Member', 'type'=>'select2', 'option' =>$user],
            [ 'name' => 'period_id', 'label' => 'period_id', 'type' => 'hidden', 'value' => $id],


            // [ 'name' => 'description', 'label' => 'Deskripsi', 'type' => 'text'],
            // ['name' => 'ket', 'label' => 'Keterangan', 'type'=>'select', 'value' => ['sa', 'tu', 'dua']]  
        ];
        $data['form_action'] = "penggajian.manual";
        $data['variable_penambah'] = Variable::where('description', 'Penambah')->get();
        $data['variable_pengurang'] = Variable::where('description', 'Pengurang')->get();
        
        // return json_encode($data['period_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)->get();
        // $data['member'] = User::where('partner_id', $id)->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.penggajian.detail-generate', $data);

    }

    public function dataSalary(Request $request){
        
        $data = Salary::with('user:name,id')->where('company_id', Auth::user()->company->id);
        // $data = Salary::with('user:name')->whereHas('user', function ($query) use ($groupIds) {
        //     return $query->whereIn('groups.id', $groupIds);
        // });

        // return json_encode($data);


        if (!empty ($request->get('period_id')) ){
            $data = $data->where('period_id', $request->get('period_id'));
        };

        if (!empty ($request->get('partner_id_filter')) ){
            $data = $data->where('partner_id', $request->get('partner_id_filter'));
        };
        


         return Datatables::of($data)
               ->editColumn('action', function($data){ return view('dashboard.penggajian.action-detail', compact('data'));})
               ->rawColumns(['action'])
               ->make(true); 

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

    $period = Period::findOrFail($request->period_id);

    $user = User::where('is_payroll', '1')->where('company_id', Auth::user()->company->id)->where('partner_id', $request->partner_id_filter)->get();
    // return json_encode($user);

    
    foreach ($user as $dt) {
        
        $schedule = Schedule::where('user_id', $dt->id)
        ->whereDate('start', '>=', $period->start)
        ->whereDate('end',   '<=', $period->end)
                    // ->whereNotNull('start_absen')
                    // ->whereNotNull('end_absen')
                    ->get();
                    
                    $jumlah_hari = $schedule->count();
                    $jumlah_absen =$schedule->whereNotNull('start_absen')->whereNotNull('end_absen');
                    $jumlah_bolos = $jumlah_hari - $jumlah_absen->count();
                    
                    $component = Component::where('user_id', $dt->id)->get();
                    // return json_encode($component);
                    $gp = $component->where('is_subject', 1)->first();
                    $gaji_pokok = $gp->jumlah;
                    
                    $pengurang = $gaji_pokok / $jumlah_hari;
                    // $pendapatan_all = $dt->gaji_pokok + $dt->tunjangan_jabatan;
                    $pendapatan_all = $component->where('sifat', 'Penambah')->sum('jumlah');
                    $potongan_reg = $component->where('sifat', 'Pengurang')->sum('jumlah');
                    $potongan_ketidakhadiran = $jumlah_bolos * $pengurang;
                    // $potongan_all = $pengurang + $dt->potongan_bpjs_kesehatan + $dt->potongan_bpjs_ketenagakerjaan + $dt->potongan_payroll;
                    $potongan_all = $potongan_reg + $potongan_ketidakhadiran;
        $gaji = $pendapatan_all - $potongan_all;
        // $uraian = [
        //         "pendapatan"=>[
        //             "Gaji Pokok" => $dt->gaji_pokok,
        //             "Tunjangan Jabatan" => $dt->tunjangan_jabatan,
        //             ],
        //         "potongan" => [
        //             "BPJS Kesehatan" => $dt->potongan_bpjs_kesehatan,
        //             "BPJS Ketenagakerjaan" => $dt->potongan_bpjs_ketenagakerjaan,
        //             "Payroll" => $dt->potongan_payroll,
        //             "Ketidakhadiran" => $pengurang
        //         ]
        //     ];


        // return json_encode($uraian);
        $salary=Salary::where("company_id", Auth::user()->company->id)
                        ->where('period_id', $request->period_id)
                        ->where('partner_id', $request->partner_id_filter)
                        ->where('user_id', $dt->id)
                        ->get();
        if($salary->count() < 1){

            $sal = Salary::create([
                'company_id' => Auth::user()->company->id,
                'user_id' => $dt->id,
                'period_id' => $request->period_id,
                'partner_id' => $request->partner_id_filter,
                'pendapatan_all' => $pendapatan_all,
                'potongan_all' => $potongan_all,
                'total_gaji' => $gaji
                ]);

                foreach ($component as $item) {
                    $researche = Detail::create([
                        // 'company_id' => Auth::user()->company->id,
                        'salary_id' => $sal->id,
                        'sifat' => $item->sifat,
                        'jumlah' => $item->jumlah,
                        'description' => $item->name
                        ]);
                }
                $xxx = Detail::create([
                    // 'company_id' => Auth::user()->company->id,
                    'salary_id' => $sal->id,
                    'sifat' => 'Pengurang',
                    'jumlah' => $potongan_ketidakhadiran,
                    'description' => 'Ketidakhadiran'
                    ]);

        }



    }

    return json_encode('success');


   }

   public function cetak_pdf($id){

    // $data['id'] = $id;
    // $data['salary'] = Salary::with('user:name,id', )findOrFail($id);
    $data['salary'] = Salary::with('user:name,id', 'period' )->findOrFail($id);
    $data['detail_penambah'] = Detail::where('salary_id', $id)->where('sifat', 'Penambah')->get();
    $data['detail_pengurang'] = Detail::where('salary_id', $id)->where('sifat', 'Pengurang')->get();
    $data['uraian'] = json_decode($data['salary']['uraian']);
    $data['company'] = strtoupper(Auth::user()->company->name);
    $data['admin'] = 'Irawan Pramudhita, SE';
    $data['signature'] = For_signature::with('signature')->where('name', 'Penggajian')->first();

    // return json_encode($data);


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

   }

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

        if ($validator->fails()) {
            return json_encode('error');
        }


        foreach ($request->variable_id as $dt) {
            $cek = Component::where('user_id', $request->user_id)->where('variable_id', $dt)->get();
        if($cek->count() < 1){

            $variable = Variable::findOrFail($dt);
            if($variable->is_subject == 1){
                $is_subject = 1;
            }else{
                $is_subject = 0;
            };
            
            $component = Component::create([
                'user_id' => $request->user_id,
                'variable_id' => $dt,
                'name' => $variable->name,
                'is_subject' => $is_subject,
                'sifat' => $variable->description
                ]);
        }

        };
          
        return json_encode('success');
        
        // return json_encode($request->all());
    }

    public function look_component(Request $request)
    {
       
        $data = Component::where('user_id', $request->data)->get();
        return json_encode($data);

    }
    public function sub_obj(Request $request)
    {
        // return json_encode($request->all());
        foreach ($request->obj as $key => $dt) {
            $data = Component::find($key);
            // Log::info($data);
            if($data != null){
                $data->jumlah = $dt ?? null;
                $data->save();
            }
        }
       return json_encode('success');
        // $data = Component::where('user_id', $request->data)->get();
        // return json_encode($data);

    }

    public function destroy_component(Request $request)
    {
        $data = Component::find($request->id);
        if($data->count() < 1){
        return json_encode('error');
        };
        $data->delete();
        return json_encode('success');

    }
    public function manual(Request $request)
    {
        $salary=Salary::where("company_id", Auth::user()->company->id)
        ->where('period_id', $request->period_id)
        // ->where('partner_id', $request->partner_id_filter)
        ->where('user_id', $request->user_id)
        ->get();
        $user = User::find($request->user_id);
        // return json_encode($user);
        $company_id = $user->company_id;
        $partner_id = $user->partner_id;
        if($salary->count() < 1){

            $sal = Salary::create([
                'company_id' => Auth::user()->company->id,
                'user_id' => $request->user_id,
                'period_id' => $request->period_id,
                'partner_id' => $partner_id
                ]);
                session()->put('success','Berhasil Input.');   
            return back();
            }
        session()->put('error','Input gagal.');
            return back();

    }

    public function look_detail(Request $request)
    {
       
        $data = Detail::where('salary_id', $request->salary_id)->get();
        return json_encode($data);

    }
    public function store_detail(Request $request)
    {
        $salary = Salary::find($request->salary_id);
        
        foreach ($request->variable_id as $dt) {
            $cek = Component::where('user_id', $salary->user_id)->where('variable_id', $dt)->first();
            $variable = Variable::where('id', $dt)->first();
            // return json_encode($variable);
            if($cek != null){
                if($cek->count() > 0){
                    
                    $component = Detail::create([
                        'salary_id' =>$request->salary_id,
                        'sifat' => $cek->sifat,
                        'jumlah' => $cek->jumlah,
                        'description' => $cek->name
                        ]);
                }
            }else{

            
            $component = Detail::create([
                'salary_id' =>$request->salary_id,
                'sifat' => $variable->description,
                'description' => $variable->name
                ]);
        }

        };
          
        return json_encode('success');
        
        // return json_encode($request->all());
    }

    public function update_detail(Request $request)
    {
        foreach ($request->obj as $key => $dt) {
            

            
            $data = Detail::find($key);
            if($data != null){
            $data->jumlah = $dt ?? null;
            $data->save();

            }
        }
        // return json_encode($request->all());

        $detail_penambah = Detail::where('salary_id', $request->salary_id)->where('sifat', 'Penambah')->sum('jumlah');
        $detail_pengurang = Detail::where('salary_id', $request->salary_id)->where('sifat', 'Pengurang')->sum('jumlah');

        $salary = Salary::find($request->salary_id);
        if($salary != null){
        $salary->pendapatan_all = $detail_penambah ?? null;
        $salary->potongan_all = $detail_pengurang ?? null;
        $salary->total_gaji = $detail_penambah - $detail_pengurang;
        $salary->save();

        }


       return json_encode('success');
    }

    public function destroy_detail(Request $request)
    {
        $data = Detail::find($request->id);
        if($data->count() < 1){
        return json_encode('error');
        };
        $data->delete();
        return json_encode('success');

    }
    
    public function cetak_report_pdf($id, $partner_id){
        
        
        // $data['id'] = $id;
        // $data['salary'] = Salary::with('user:name,id', )findOrFail($id);
        // return json_encode([$id, $partner_id]);
        $data['salary'] = Salary::with('user')->where('period_id', $id)->where('partner_id', $partner_id)->get();
        $data['partner'] = Partner::findOrFail($partner_id);
        $data['period'] = Period::findOrFail($id);
        // return json_encode($data);
        // $report = Report::with('report_detail')->findOrFail($id);
        // $data['report'] = $report;
        // $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';
        $data['signature'] = For_signature::with('signature')->where('name', 'Akuntansi')->first();

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

}