<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\View;
use App\Invoice;
use App\Partner;
use App\For_signature;
use App\Transaction;
use App\Invoice_detail;
use Illuminate\Support\Facades\Validator;
use DataTables;
use Illuminate\Support\Facades\Auth;
use PDF;


class InvoiceController extends Controller
{
    public function __construct()
    {
        // $this->middleware('auth');
        $this->middleware('akuntan');
        // $this->middleware('admin');
        $this->pageTitle = 'Invoice';
        $this->invoiceActive = 'active';
    }
    public function index()
    {
        $data = (array)$this;
        $partner = Partner::all();

        $data['form'] = [
            [ 'name' => 'invoice_number', 'label' => 'No. Invoice', 'type' => 'text'],
            // [ 'name' => 'description', 'label' => 'Nama Tagihan', 'type' => 'text'],
            // [ 'name' => 'jumlah', 'label' => 'besaran', 'type' => 'number'],
            [ 'name' => 'ppn', 'label' => 'PPN', 'type' => 'number'],
            [ 'name' => 'pph', 'label' => 'PPH', 'type' => 'number'],
            [ 'name' => 'atas_nama', 'label' => 'Atas Nama', 'type' => 'text'],
            [ 'name' => 'expired', 'label' => 'Expired', 'type' => 'date'],
            ['name' => 'partner_id', 'label' => 'Partner', 'type'=>'select', 'option' =>$partner],
            ['name' => 'status', 'label' => 'Status', 'type'=>'select', 'option' => [
                        ['id'=>3, 'name'=>'Ditolak'],
                        ['id'=>2, 'name'=>'Disetujui'],
                        ['id'=>1, 'name'=>'Diajukan'],
                        ['id'=>0, 'name'=>'Tagihan']
                        ]  
                    ]

            // ['name' => 'ket', 'label' => 'Keterangan', 'type'=>'select', 'value' => ['sa', 'tu', 'dua']]  
        ];
        $data['form_action'] = "invoice.store";
        $data['form_update'] = "invoice.update";
        // return json_encode($data);
        return View::make('dashboard.invoice.index', $data);
    }
    public function indexData(Request $request){
        $data = Invoice::with('partner');
         return Datatables::of($data)
               ->editColumn('action', function($data){ return view('dashboard.invoice.index-action', compact('data'));})
               ->rawColumns(['action'])
               ->make(true); 

   }
   public function store(Request $request)
   {
    //    return json_encode($request->all());
    //    return json_encode(array_sum($request->jumlah_detail));
       $validator = Validator::make($request->all(), [
            // 'description' => 'required',
            'expired' => 'required',
            'partner_id' => 'required',
            'ppn' => 'required',
            'pph' => 'required',
            'atas_nama' => 'required',
            'invoice_number' => 'required',

        ]);

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

      
        $jumlah = array_sum($request->jumlah_detail);
        
        $total =  ($jumlah + $request->ppn) - $request->pph;
        $invoice = Invoice::create([
            // 'description' => $request->description,
            'expired' => $request->expired,
            'partner_id' => $request->partner_id,
            'status' => $request->status,
            'jumlah' => $jumlah,
            'ppn' => $request->ppn,
            'pph' => $request->pph,
            'invoice_number' => $request->invoice_number,
            'total' => $total,
            'atas_nama' => $request->atas_nama

            ]);

            foreach (array_combine($request->nama_tagihan, $request->jumlah_detail) as $item => $detail) {
                // foreach ($request->jumlah_detail as $detail) {
                Invoice_detail::create([
                    'description' => $item,
                    'jumlah_detail' => $detail,
                    'invoice_id' => $invoice->id
                    ]);
            // }
        };
        
        session()->put('success','Berhasil Input.');   
        return back();
        
    }

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

    Invoice_detail::create([
        'description' => $request->nama_tagihan,
        'jumlah_detail' => $request->jumlah_detail,
        'invoice_id' => $request->id_invoice
        ]);
        
        $subtotal = Invoice_detail::where('invoice_id', $request->id_invoice)->sum('jumlah_detail');

        // return json_encode($subtotal);
        $data = Invoice::find($request->id_invoice);

        $total =  ($subtotal + $data->ppn) - $data->pph;
        $data->jumlah = $subtotal;
        $data->total = $total;

        $data->save();

        session()->put('success','Berhasil Input.');   
        return back();
   }

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

    public function destroy_detail($id)
    {
        $invoice_detail = Invoice_detail::find($id);
        
        
        if($invoice_detail->count() < 1){
            session()->put('error','Gagal hapus.');
            return back();
        };
        $invoice_detail->delete();
        $subtotal = Invoice_detail::where('invoice_id', $invoice_detail->invoice_id)->sum('jumlah_detail');

        // return json_encode($subtotal);
        $data = Invoice::find($invoice_detail->invoice_id);

        $total =  ($subtotal + $data->ppn) - $data->pph;
        $data->jumlah = $subtotal;
        $data->total = $total;

        $data->save();

        session()->put('success','Berhasil Hapus.');
            return back();
    }
    public function look(Request $request)
    {
       
        $data = Invoice::with('invoice_detail')->findOrFail($request->data);
        return json_encode($data);

    }
    public function update(Request $request)
    {
        // return json_encode($request->all());
        $validator = Validator::make($request->all(), [
            // 'description' => 'required',
            'partner_id' => 'required'
        ]);
        if ($validator->fails()) {
            session()->put('error','Input gagal.');
            return back();
        }
        // $total =  ($request->jumlah + $request->ppn) - $request->pph;

        $data = Invoice::find($request->id);
        $detail_invoice = Invoice_detail::where('invoice_id', $data->id)->get('description');
        if($data->status != '2' && $request->status == '2'){
            $partner = Partner::find($request->partner_id);
            // return json_encode($partner->name);

            // foreach($detail_invoice as $item){

            // }

            // $desc = json_encode($detail_invoice);
            $aman = [];
            foreach($detail_invoice as $item){
                array_push($aman, $item->description);
            };
            // $aman = $detail_invoice->description
            $ramai = implode(", ", $aman);
                $transaction = [
                    'jumlah' => $data->total,
                    'description' => 'Setoran : '.$ramai.' (' .$partner->name . ')',
                    'jenis' => 'debet',
                    'is_cash' => '0',
                    'company_id' => Auth::user()->company->id
                ];
                Transaction::create($transaction);
        }
        // return json_encode('ini');


        $data->expired = $request->expired;
        $data->description = $request->description;
        $data->partner_id = $request->partner_id;
        $data->status = $request->status;
        // $data->jumlah = $request->jumlah;
        // $data->ppn = $request->ppn;
        // $data->pph = $request->pph;
        $data->atas_nama = $request->atas_nama;
        $data->invoice_number = $request->invoice_number;
        // $data->total = $total;
        $data->save();
        session()->put('success','Berhasi edit!');
        return back();
    }

    public function cetak_pdf($id){

        $data['invoice'] = Invoice::with('partner', 'invoice_detail')->findOrFail($id);
        $data['company'] = strtoupper(Auth::user()->company->name);
        $data['description'] = strtoupper(Auth::user()->company->description);
        $data['admin'] = 'Irawan Pramudhita, SE';
        $data['signature'] = For_signature::with('signature')->where('name', 'Invoice')->first();
        $data['rekening'] = env('REKENING');
        // return json_encode($data);
    
    
        $pdf = PDF::loadView('dashboard.invoice.cetak-prev', $data)->setPaper('a4', 'potrait');
            return $pdf->stream('invoice.pdf');
            // return $pdf->download('invoice.pdf');
    
       }

       public function cetak_bill($id){

        $data['invoice'] = Invoice::with('partner', 'invoice_detail')->findOrFail($id);
        $data['company'] = strtoupper(Auth::user()->company->name);
        $data['description'] = strtoupper(Auth::user()->company->description);
        $data['admin'] = 'Irawan Pramudhita, SE';
        $data['signature'] = For_signature::with('signature')->where('name', 'Invoice')->first();
        $data['rekening'] = env('REKENING');
        $angka = $this->penyebut($data['invoice']['total']).' RUPIAH';
        $data['angka'] = strtoupper($angka);



        // return json_encode($data['invoice']);
        // return ;
    
    
        $pdf = PDF::loadView('dashboard.invoice.cetak-bill', $data)->setPaper('a4', 'potrait');
            return $pdf->stream('invoice.pdf');
            // return $pdf->download('invoice.pdf');
    
       }

public function penyebut($nilai) {
		$nilai = abs($nilai);
		$huruf = array("", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas");
		$temp = "";
		if ($nilai < 12) {
			$temp = " ". $huruf[$nilai];
		} else if ($nilai <20) {
			$temp = $this->penyebut($nilai - 10). " belas";
		} else if ($nilai < 100) {
			$temp = $this->penyebut($nilai/10)." puluh". $this->penyebut($nilai % 10);
		} else if ($nilai < 200) {
			$temp = " seratus" . $this->penyebut($nilai - 100);
		} else if ($nilai < 1000) {
			$temp = $this->penyebut($nilai/100) . " ratus" . $this->penyebut($nilai % 100);
		} else if ($nilai < 2000) {
			$temp = " seribu" . $this->penyebut($nilai - 1000);
		} else if ($nilai < 1000000) {
			$temp = $this->penyebut($nilai/1000) . " ribu" . $this->penyebut($nilai % 1000);
		} else if ($nilai < 1000000000) {
			$temp = $this->penyebut($nilai/1000000) . " juta" . $this->penyebut($nilai % 1000000);
		} else if ($nilai < 1000000000000) {
			$temp = $this->penyebut($nilai/1000000000) . " milyar" . $this->penyebut(fmod($nilai,1000000000));
		} else if ($nilai < 1000000000000000) {
			$temp = $this->penyebut($nilai/1000000000000) . " trilyun" . $this->penyebut(fmod($nilai,1000000000000));
		}     
		return $temp;
	}
}