<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use App\Report;
use App\Salary;
use App\Invoice;
use App\Transaction;
use App\Report_detail;
use App\For_signature;
use Illuminate\Support\Facades\Validator;
use DataTables, DB, PDF;
use Illuminate\Support\Facades\Auth;


class ReportController extends Controller
{
    public function __construct()
    {
        // $this->middleware('auth');
        $this->middleware('akuntan');
        $this->pageTitle = 'Laporan';
        $this->akuntansiActive = 'active';
    }
    public function index()
    {
        $this->reportActive = 'active';
        $data = (array)$this;
        $report = Report::select('id', DB::raw("CONCAT(start,end) as name"))->orderBy('created_at', 'desc')->get();

        // return json_encode($report);

        $data['form'] = [
            [ 'name' => 'tanggal', 'label' => 'Tanggal', 'type' => 'daterange'],
            ['name' => 'report_id_sebelumnya', 'label' => 'Acuan saldo dari laporan', 'type'=>'select', 'option' =>$report],

            // [ 'name' => 'description', 'label' => 'Deskripsi', 'type' => 'text'],
            // ['name' => 'ket', 'label' => 'Keterangan', 'type'=>'select', 'value' => ['sa', 'tu', 'dua']]  
        ];
        $data['form_action'] = "report.store";
        $data['form_update'] = "report.update";
        // return json_encode($data);
        return View::make('dashboard.report.index', $data);
    }
    public function indexData(Request $request){
        $data = Report::all();
         return Datatables::of($data)
               ->editColumn('action', function($data){ return view('dashboard.report.index-action', compact('data'));})
               ->editColumn('start', function ($data) {     
                
                    return date('d F Y', strtotime($data->start));
                    })
                ->editColumn('end', function ($data) {     
                
                        return date('d F Y', strtotime($data->end));
                        })
               ->rawColumns(['action', 'start', 'end'])
               ->make(true); 

   }

    public function store(Request $request)
    {
        // return json_encode($request->all());
        
        
        $validator = Validator::make($request->all(), [
            'tanggal' => 'required',
            // 'description' => 'required',
        ]);
        
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $date = explode(' - ', $request->tanggal);
        $start = $date[0];
        $end = date('Y-m-d H:i:s', strtotime($date[1] . ' +1 day'));

        // $ee = new DateTime($end);
                            // return json_encode($end);


        $salary = Salary::where('company_id', Auth::user()->company->id)
                            ->whereBetween('updated_at', [$start, $end])
                            ->get();
                            // return json_encode($salary);

        $invoice = Invoice::with('partner')->whereHas('partner', function ($query) {
                        $query->where('company_id', Auth::user()->company->id);
                        })->where('status', 2)
                        ->whereBetween('updated_at', [$start, $end])
                        ->get();
                        // return json_encode($invoice);


        $transaction = Transaction::where('company_id', Auth::user()->company->id)
                        ->whereBetween('updated_at', [$start, $end])
                        ->get();
                        // return json_encode($transaction->where('jenis', 'kredit')->sum('jumlah'));
                        // return json_encode($transaction->where('jenis', 'debet')->sum('jumlah'));
                        // return json_encode($transaction);
        $kredit = $salary->sum('total_gaji') + $transaction->where('jenis', 'kredit')->sum('jumlah');
        $debet = $invoice->sum('jumlah') + $transaction->where('jenis', 'debet')->sum('jumlah');

        if (!empty ($request->report_id_sebelumnya) ){   
            $report = Report::find($request->report_id_sebelumnya);
            $saldo_awal =  $report->saldo; 
        }else{
            $saldo_awal = 0;
        };

        $saldo = ($saldo_awal + $debet) - $kredit;
        // return json_encode($saldo);


        $insert = Report::create([
            'start' => $start,
            'end' => $date[1],
            'company_id' => Auth::user()->company->id,
            'report_id_sebelumnya' => $request->report_id_sebelumnya ?? null,
            'total_debet' => $debet + $saldo_awal,
            'total_kredit' => $kredit,
            'saldo' => $saldo
            // 'description' => $request->description

            ]);

            $rep = Report_detail::create([
                'report_id' => $insert->id,
                'description' => 'Saldo Awal',
                'jenis' => 'debet',
                'jumlah' => $saldo_awal
                ]);

// ------------------gaji------------------
                $repx = Report_detail::create([
                    'report_id' => $insert->id,
                    'description' => 'Pembayaran Gaji',
                    'jenis' => 'kredit',
                    'jumlah' => $salary->sum('total_gaji')
                    ]);


            foreach ($invoice as $key => $dt) {
                $repz = Report_detail::create([
                    'report_id' => $insert->id,
                    'description' => $dt->description.' ('. $dt->partner->name.')',
                    'jenis' => 'debet',
                    'jumlah' => $dt->jumlah
                    ]);
            }

            foreach ($transaction as $key => $dt) {
                if($dt->is_cash == '1'){
                    // return json_encode('ok');
                    $is_cash = '1';
                }else{
                    $is_cash = '0';
                }
                $rep2 = Report_detail::create([
                    'report_id' => $insert->id,
                    'description' => $dt->description,
                    'jenis' => $dt->jenis,
                    'is_cash' => $is_cash,
                    'jumlah' => $dt->jumlah
                    ]);
            }

        

        session()->put('success','Berhasil Input.');   
        return redirect('/report');
        
    }

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

    }
    public function update(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
        ]);
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        $data = Report::find($request->id);
        $data->name = $request->name;
        // $data->description = $request->description;
        $data->save();
        session()->put('success','Berhasi edit!');
        return redirect('/report');  
    }
    public function cetak_pdf($id){
        
        
        // $data['id'] = $id;
        // $data['salary'] = Salary::with('user:name,id', )findOrFail($id);
        $report = Report::with('report_detail')->findOrFail($id);
        // return json_encode($report);
        $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();

        
        // return json_encode($data);
        
        $pdf = PDF::loadView('dashboard.report.cetak-prev', $data)->setPaper('a4', 'potrait');
            return $pdf->stream('Laporan Akuntansi.pdf');
            // return $pdf->download('Laporan Akuntansi.pdf');
    
       }
       public function custom_pdf($id){
        
        
        // $data['id'] = $id;
        // $data['salary'] = Salary::with('user:name,id', )findOrFail($id);
        $report = Report::with('report_detail')->findOrFail($id);
        
        $start = $report->start;
        $end = date('Y-m-d H:i:s', strtotime($report->end . ' +1 day'));
        
        
        $salary = Salary::with('partner')->where('company_id', Auth::user()->company->id)
            ->whereBetween('updated_at', [$start, $end])
            ->get();
            $data['gaji'] = $salary->sum('total_gaji');

        $data['invoice'] = Invoice::with('partner')->whereHas('partner', function ($query) {
            $query->where('company_id', Auth::user()->company->id);
            })->where('status', 2)
            ->whereBetween('updated_at', [$start, $end])
            ->get();
            $data['total_invoice'] = $data['invoice']->sum('jumlah');
            $data['saldo']=$data['total_invoice']-$data['gaji'];
        
        // return json_encode($invoice);





        

        $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();

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