<?php

namespace App\Http\Controllers;

use Mike42\Escpos\Printer; 
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
use Mike42\Escpos\EscposImage;
use Mike42\Escpos\PrintConnectors\RawbtPrintConnector;
use Mike42\Escpos\CapabilityProfile;

use Illuminate\Http\Request;
use DataTables;
use Auth;
use DB;
use Session;
use Redirect;

use App\User;
use App\City;
use App\User_logs;
use App\Setting;
use App\ProjectRumah;
use App\MSRumah;
use App\Transaksi;
use App\Customer;
use App\Cicilan;
use App\Referensi;
use App\Bank;


class TransaksiController extends Controller
{
    
    public function index(){
        
        $projek = ProjectRumah::all();
        $cust   = Customer::where('is_customer',1)
                                ->orderBy('cus_name')
                                ->get();
                                
        $ref    = Referensi::orderBy('nama')
                                ->get();
                                
        $bnk    = Bank::orderBy('nama')                                
                                ->get();
        
        return view('transaksi.index', compact('projek','cust','ref','bnk'));
    }
    
    public function datatransaksi(){
    
        $tr = DB::table('dt_transaksi as A')
                    ->select('A.*','B.project_name','C.cus_name','D.cluster','D.block','D.nomor','D.luastanah','D.luasrumah','D.lantai','A.status_trx')
                    ->leftjoin ('ms_project as B', function($join){
                        $join->on('A.project_id', '=', 'B.id');
                    })
                    ->leftjoin('ms_customer as C', function($join){
                        $join->on('A.cust_id', '=', 'C.id_cust');
                    })
                    ->leftjoin('ms_rumah as D', function($join){
                        $join->on('A.rumah_id', '=', 'D.id');
                    })
                    ->where('A.is_cancel',0)
                    ->orderBy('A.trans_no','DESC')
                    ->get();
                        
        $data=[];
        foreach($tr as $dt){
            
            $byr='';
            switch($dt->status_trx){
                case "1": $byr="KPR"; break;
                case "2": $byr="CASH BERTAHAP"; break;
                case "3": $byr="CASH KERAS";break;
            }           
            
            $row=[];
            $row[] = $dt->trans_no;
            $row[] = $dt->tgl_book;
            $row[] = $dt->project_name;
            $row[] = $dt->cluster.'/'. $dt->block.'/'.$dt->nomor;
            $row[] = $dt->cus_name;
            $row[] = '<div class="text-right" style="font-weight:bold">'.number_format($dt->harga_rumah).'</div>';
            $row[] = '<div class="text-right">'.number_format($dt->total_cicilan).'</div>';
            $row[] = $byr;
        /*    
            $row[] = '<div class="btn-btn">
                        <a onclick="infotrx('.$dt->id.')" class="btn btn-info btn-sm"><i class="fa fa-info"></i></a>
                        <a onclick="editinfo('.$dt->id.')" class="btn btn-success btn-sm"><i class="fa fa-pencil"></i></a>
                        <a onclick="pembayaran('.$dt->id.')" class="btn btn-primary btn-sm"><i class="fa fa-dollar"></i></a>
                      </div>';
        */
            $row[]=
	              '<div class="btn-group">
                    <a  class="btn btn-flat btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    </a>
                        <ul class="dropdown-menu dropdown-menu-right" style="border:2px black solid;" id="dropMenu">
                            <li><a onclick="infotrx('.$dt->id.')"><i class="fa fa-info"></i>Informasi</a></li>
                            <li><a onclick="editinfo('.$dt->id.')"><i class="fa fa-pencil"></i>Edit Keterangan </a></li>
                            <li><a onclick="pembayaran('.$dt->id.')"><i class="fa fa-dollar"></i>Pembayaran</a></li>
                            <li><a onclick="pembatalan('.$dt->id.')"><i class="fa fa-times"></i>Cancel/Batal</a></li>
                            <li><a onclick="pengajuankpr('.$dt->id.')"><i class="fa fa-file-text-o"></i>Pengajuan KPR</a></li>
                        </ul>
                    </div>';
                       

            $data[]=$row;
        }
        
        return response()->json(["data"=>$data]);
        
    }
    
    public function store(Request $request){
        
        $prj    = ProjectRumah::find($request['prj']);
        $rmh    = MSRumah::find($request['id_rmh']);
        //$dp     = $request['dp'];
        //$tpdp   = $request['tpdp'];
        $tgl    = $request['tgltr'];
        
        //if($tpdp=='' || is_null($tpdp)){ return json_encode(['msg'=>'error2']); }
        
        $notrx   = $this->cekNoTrans($tgl);
        $noorder = $this->cekNoOrder($prj->initial, $tgl);
        
        $trx = new Transaksi;
        
        $trx->trans_no      = $notrx;
        $trx->order_no      = $noorder;
        $trx->project_id    = $prj->id;
        $trx->rumah_id      = $rmh->id;
        $trx->cust_id       = $request['cus'];
        $trx->tgl_book      = $tgl;
        $trx->status_trx    = $request['byr'];
        $trx->bank_id       = $request['kdbank'];
        $trx->harga_rumah   = $rmh->harga;
       // $trx->total_dp      = $dp;
        $trx->ref_id        = $request['ref'];
        $trx->deskripsi     = $request['ket'];
        
        //if($rmh->harga==$dp){ $trx->is_lunas="1"; }
        
        $trx->user_id       = Auth::user()->id;
        $trx->save();

        $rmh->is_sold=1;
        $rmh->update();
        
        /*
        if($dp > 0){
            $this->simpanDP($notrx, $dp, $tpdp);
        }
        */
        
	// insert logs
		$usrnm	= Auth::user()->username;
		
		$title		= 'New Transaksi';
		$content	= 'Project '.$prj->project_name.'-'.$rmh->cluster.'/'.$rmh->block.'/'.$rmh->nomor.' berhasil terjual';
		$userid	    = Auth::user()->id;

        User_logs::UserLogs($title, $content, $userid);
        		
        echo json_encode(["msg"=>"success"]);
    }
    
    public function simpanDP($notrx, $dp, $tpdp){
        
        $trx    = Transaksi::where('trans_no',$notrx)->first();
        $prj    = ProjectRumah::find($trx->project_id);
        $rmh    = MSRumah::find($trx->rumah_id);
        $cus    = Customer::find($trx->cust_id);
        
        $ketrmh = '';
        if($rmh->cluster==''){ 
            $ketrmh='BLOCK: '.$rmh->block.' / NOMOR: '.$rmh->nomor; 
        }else{ 
            $ketrmh='CLUSTER: '.$rmh->cluster.' / BLOCK: '.$rmh->block.' / NOMOR: '.$rmh->nomor; 
        }
        
        
        $ccl = new Cicilan;
        $no  = $this->cekNoCicilan();

        $ccl->trans_id      = $trx->id;
        $ccl->cicil_no      = $no;
        $ccl->cicil_tgl     = date('Y-m-d');
        $ccl->cicil_nominal = $dp;
        $ccl->cicil_type    = $tpdp;
        $ccl->is_dp         = '1';
        $ccl->deskripsi     = 'Down Payment atas Pembelian Rumah di: '."\n".$prj->project_name."\n".$ketrmh;
        $ccl->user_id       = Auth::user()->id;
        $ccl->save();

        $trx->total_cicilan = $dp;
        $trx->sisa          = $trx->harga_rumah - $dp;
        $trx->update();

	// insert logs
		$usrnm	= Auth::user()->username;

		$title		= 'Down Payment/Booking Fee ';
		$content	= $no.' DP Pembelian Rumah '.$cus->cus_name.' sebesar Rp.'.$dp.' berhasil disimpan '.$usrnm;
		$userid	    = Auth::user()->id;

		User_logs::UserLogs($title, $content, $userid);
		
		return true;
        
    }
            
    
    public static function cekNoTrans($tgl){
    	/* cek no terakhir */
		$notr	= '';
		$tahun	= date('Y', strtotime($tgl));    //date('Y');
		$bulan  = date('m', strtotime($tgl));     //date('m');
		$nomor	="TRX/".$tahun.$bulan."/";		/* TRX/202308/0001*/
			
		$ada_no	= DB::table('dt_transaksi')
						->select(DB::raw('SUBSTR(MAX(trans_no),12,4) as last_no'))
						->where('trans_no', 'LIKE', "$nomor%" )
						->first();
			
		if (!empty($ada_no))
		{
			$no	= $ada_no->last_no + 1;
				
			$nomorbaru 	= sprintf("%04s", $no);		//format: IN/202101/0001
			$notr = $nomor.$nomorbaru;
			
		} else {
			$nomorbaru = "0001";
			$notr = $nomor.$nomorbaru;
		}
		
		return $notr;
    }	
    
    
    public static function cekNoOrder($init, $tgl){
        
    	/* cek no terakhir */
		$noorder	= '';
		$tahun	= date('Y', strtotime($tgl));    //date('Y');
		$bulan  = date('m', strtotime($tgl));     //date('m');
        
        $bln='';
        switch($bulan){
            case '01': $bln='I';break;
            case '02': $bln='II';break;  
            case '03': $bln='III';break;  
            case '04': $bln='IV';break;  
            case '05': $bln='V';break;  
            case '06': $bln='VI';break;  
            case '07': $bln='VII';break;  
            case '08': $bln='VIII';break;  
            case '09': $bln='IX';break;  
            case '10': $bln='X';break;  
            case '11': $bln='XI';break;  
            case '12': $bln='XII';break;  
        }
		
		$nomor ="/".$init."/".$bln."/".$tahun;      //0001/RCP/IX/2023
			
		$ada_no	= DB::table('dt_transaksi')
						->select(DB::raw('SUBSTR(MAX(order_no),1,4) as last_no'))
						->where('order_no', 'LIKE', "%$nomor%" )
						->first();
			
		if (!empty($ada_no))
		{
			$no	= $ada_no->last_no + 1;
				
			$nomorbaru 	= sprintf("%04s", $no);		//format: IN/202101/0001
			$noorder = $nomorbaru.$nomor;
			
		} else {
			$nomorbaru = "0001";
			$noorder = $nomorbaru.$nomor;
		}
		
		return $noorder;
    }	    

    public function edit($id){
        $dt = Transaksi::find($id);
        $prj= ProjectRumah::find($dt->project_id);
        $rmh= MSRumah::find($dt->rumah_id);
        $cus= Customer::find($dt->cust_id);

        $tp='';
        switch($dt->status_trx){
            case "1": $tp='KPR'; break;
            case "2": $tp='CASH KERAS';break;
            case "3": $tp='CASH BERTAHAP';break;
        }

        $data=["id_prj"=>$prj->id, "id_cust"=>$cus->id_cust, "id_rumah"=>$rmh->id, "id"=>$dt->id, "cluster"=>$rmh->cluster, "block"=>$rmh->block,
                "nomor"=>$rmh->nomor, "luastanah"=>$rmh->luastanah, "luasrumah"=>$rmh->luasrumah, "harga_rumah"=>$dt->harga_rumah,
                "total_dp"=>$dt->total_dp, "status_trx"=>$dt->status_trx, "ref_id"=>$dt->ref_id, "deskripsi"=>$dt->deskripsi,
                "project_name"=>$prj->project_name, "cus_name"=>$cus->cus_name, "address"=>$cus->cus_address, "trans_no"=>$dt->trans_no,
                "total_cicilan"=>$dt->total_cicilan,"sisa"=>$dt->harga_rumah-$dt->total_cicilan, "tgl_book"=>$dt->tgl_book, "tipe"=>$tp,"bank_id"=>$dt->bank_id];
        
        echo json_encode($data);
        
        //$hasil = number_format($angka,0,',','.');
        //echo json_encode(array_merge(json_decode($prj, true), json_decode($rmh, true), json_decode($cus, true), json_decode($dt, true)));

    }

    public function show($id){
        $dt = ProjectRumah::find($id);
        echo json_encode($dt);
    }
    
    public function update(Request $request, $id){

        $trx = Transaksi::find($id);
        
        $trx->status_trx    = $request['byr'];
        $trx->bank_id       = $request['kdbank'];
        $trx->ref_id        = $request['ref'];
        $trx->deskripsi     = $request['ket'];
        $trx->update();

	// insert logs
		$usrnm	= Auth::user()->username;
		
		//$userlog = New User_logs;
		$title		= 'Edit Transaksii';
		$content	= 'Transaksi '.$trx->trans_no.' diedit oleh '.$usrnm;
		$userid	    = Auth::user()->id;
        
        User_logs::UserLogs($title, $content, $userid);
        
        echo json_encode(["msg"=>"success"]);

    }
 
    public function infotransaksi($id){
        
        $dt = Transaksi::find($id);
        $prj = ProjectRumah::find($dt->project_id);
        $rmh = MSRumah::find($dt->rumah_id);
        $cus = Customer::find($dt->cust_id);
        
        if(is_null($dt->ref_id)){ $ref='';}else{ $ref=Referensi::get_referensi($dt->ref_id)->nama; }
        
        $byr='';
        switch($dt->status_trx){
            case "1": $byr="KPR"; break;
            case "2": $byr="CASH BERTAHAP"; break;
            case "3": $byr="CASH KERAS";break;
        }
        
        
        $data=[];
        
        $row=[];
        $row[]="NO. TRANSAKSI ";
        $row[]=$dt->trans_no;
        $data[]=$row;
        
        $row=[];
        $row[]="TGL. TRANSAKSI ";
        $row[]= tanggal_indonesia($dt->tgl_book, false);
        $data[]=$row;
        
        $row=[];
        $row[]="Perumahan";
        $row[]=$prj->project_name;
        $data[]=$row;
        
        $row=[];
        $row[]="CLUSTER/BLOCK/NO";
        $row[]=$rmh->cluster.'/'.$rmh->block.'/'.$rmh->nomor;
        $data[]=$row;
        
        $row=[];
        $row[]="TYPE";
        $row[]=$rmh->luasrumah.'/'.$rmh->luastanah;
        $data[]=$row;
        
        $row=[];
        $row[]="PEMBELI";
        $row[]=$cus->cus_name.'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; HP. '.$cus->cus_hp;
        $data[]=$row;
        
        $row=[];
        $row[]="HARGA RUMAH";
        $row[]=number_format($dt->harga_rumah);
        $data[]=$row;
        
        $row=[];
        $row[]="TYPE PEMBAYARAN";
        $row[]=$byr;
        $data[]=$row;
        
        $row=[];
        $row[]="TOTAL DP/CICILAN";
        $row[]='<div style="font-weight:bold">'.number_format($dt->total_cicilan).'</div>';       //.'&nbsp;&nbsp;<a onclick="infocicilan('.$id.')" class="btn btn-sm btn-info">..</a>';
        $data[]=$row;        

        $row=[];
        $row[]="REFERENSI";
        $row[]=$ref;
        $data[]=$row;

        $row=[];
        $row[]="KETERANGAN";
        $row[]=$dt->deskripsi;
        $data[]=$row;
        
        $row=[];
        $row[]='';
        $row[]='';
        $data[]=$row;
        
        return response()->json(["data"=>$data]);
        
    }
    
    function datacicilan($id){
        
        $trx= Transaksi::find($id);
        $dt = Cicilan::where('trans_id', $id)
                        ->get();

        $ttl = 0;
                        
        $data=[];
        foreach($dt as $cc){
            
            $tp='';
            switch($cc->cicil_type){
                case "1": $tp="CASH"; break;
                case "2": $tp="TRANSFER"; break;
                case "3": $tp="CEK/GIRO"; break;
            }
            
            $ttl += $cc->cicil_nominal;
            $pct = $cc->cicil_nominal/$trx->harga_rumah*100;
            
            $row=[];
            $row[]=tanggal_indonesia($cc->cicil_tgl, false);
            $row[]=$cc->cicil_no;
            $row[]='<div class="text-right">'.format_uang($cc->cicil_nominal).'&nbsp;&nbsp;</div>';
            $row[]='<div class="text-center">'.number_format($pct,2).'&nbsp;&nbsp;</div>';
            $row[]=$tp;
            $row[]=$cc->deskripsi;
            $row[] = '<div class="btn-btn">
                        <a onclick="printkwt('.$cc->id.')" class="btn btn-sm btn-flat"><i class="fa fa-print"></i></a>
                      </div>';

            
            $data[]=$row;
        }
        
        $trx->total_cicilan = $ttl;
        $trx->update();
        
        return response()->json(["data"=>$data]);
                        
    }
    
    function simpanCicilan(Request $request){
        
        $idtrx  = $request['id2'];
        $trx    = Transaksi::find($idtrx);
        $cus    = Customer::find($trx->cust_id);
        
        $ccl = new Cicilan;
        $no  = $this->cekNoCicilan();
        //return json_encode(['msg'=>'success']);
        
        $ccl->trans_id      = $idtrx;
        $ccl->cicil_no      = $no;
        $ccl->cicil_tgl     = $request['tglcicil'];
        $ccl->cicil_nominal = $request['nom'];
        $ccl->cicil_type    = $request['tpcicil'];
        $ccl->persentase    = $request['persen'];
        $ccl->deskripsi     = $request['ketrg'];
        $ccl->user_id       = AUth::user()->id;
        
        $ccl->save();
        
        $trx->total_cicilan += $request['nom'];
        $trx->sisa          -= $request['nom'];
        
        if(( $trx->total_cicilan + $request['nom']) == $trx->harga_rumah){ $trx->is_lunas=1; }
        
        $trx->update();

	// insert logs
		$usrnm	= Auth::user()->username;
		
		$title		= 'Cicilan';
		$content	= $no.' Cicilan '.$cus->cus_name.' sebesar Rp.'.$request['nom'].' berhasil disimpan '.$usrnm;
		$userid	    = Auth::user()->id;

		User_logs::UserLogs($title, $content, $userid);
		
        echo json_encode(["msg"=>"success"]);        
        
    }
    
    public static function cekNoCicilan(){
    	/* cek no terakhir */
		$notr	= '';
		$tahun	= date('y');
		$bulan  = date('m');
		$nomor	="KWT/".$tahun.$bulan."/";		/* CCL/2308/0001*/
			
		$ada_no	= DB::table('dt_cicilan')
						->select(DB::raw('SUBSTR(MAX(cicil_no),10,4) as last_no'))
						->where('cicil_no', 'LIKE', "$nomor%" )
						->first();
			
		if (!empty($ada_no))
		{
			$no	= $ada_no->last_no + 1;
				
			$nomorbaru 	= sprintf("%04s", $no);		//format: IN/202101/0001
			$notr = $nomor.$nomorbaru;
			
		} else {
			$nomorbaru = "0001";
			$notr = $nomor.$nomorbaru;
		}
		
		return $notr;
    }			        
    
    function printkwt($id){
        
        $cc = Cicilan::find($id);
        $trx = Transaksi::find($cc->trans_id);
        $cus = Customer::find($trx->cust_id);
        $prj = ProjectRumah::find($trx->project_id);
        $rmh = MSRumah::find($trx->rumah_id);

        return view('transaksi.kwitansi', compact('cc','trx','cus', 'prj','rmh'));
    }
    
    function testkwt(){
        
        return view('transaksi.teskwitansi');
        
    }
        
    
    function pengajuanKPR($id){
        
        $dt = Transaksi::find($id);
        $prj= ProjectRumah::find($dt->project_id);
        $rmh= MSRumah::find($dt->rumah_id);
        $cus= Customer::find($dt->cust_id);
        
        if($dt->status_trx=="1"){
            return view('transaksi.suratkpr', compact('dt','prj','rmh','cus'));
        }else{
            return back();
        }
        
    }
    
    public function batalTransaksi(Request $request, $id){
        
        $dt = Transaksi::find($id);
        $prj = ProjectRumah::find($dt->project_id);
        $rmh = MSRumah::find($dt->rumah_id);
        
        $rmh->is_sold="0";
        $rmh->update();
        
        $dt->is_cancel  = "1";
        $dt->deskripsi  = $request['ketx'];
        $dt->total_dp   = $request['dpx'];
        $dt->user_id    = Auth::user()->id;
        $dt->update();

		$usrnm	= Auth::user()->username;
		
		$title		= 'Batal Transaksi';
		$content	= $prj->project_name.' '.$rmh->cluster.'/'.$rmh->block.'/'.$rmh->nomor.' dibatalkan oleh '.$usrnm;
		$userid	    = Auth::user()->id;

		User_logs::UserLogs($title, $content, $userid);
		
        echo json_encode(["msg"=>"success"]);      
        
    }    
    
    public function bataltrx(){
        return view('transaksi.bataltrx');
    }
    
    public function dataBatal(){
    
        $tr = DB::table('dt_transaksi as A')
                    ->select('A.*','B.initial','C.cus_name','D.cluster','D.block','D.nomor','D.luastanah','D.luasrumah','D.lantai','A.deskripsi')
                    ->leftjoin ('ms_project as B', function($join){
                        $join->on('A.project_id', '=', 'B.id');
                    })
                    ->leftjoin('ms_customer as C', function($join){
                        $join->on('A.cust_id', '=', 'C.id_cust');
                    })
                    ->leftjoin('ms_rumah as D', function($join){
                        $join->on('A.rumah_id', '=', 'D.id');
                    })
                    ->where('A.is_cancel',1)
                    ->orderBy('A.trans_no','DESC')
                    ->get();
                        
        $data=[];
        foreach($tr as $dt){
            
            $row=[];
            $row[] = $dt->trans_no;
            $row[] = $dt->initial;
            $row[] = $dt->cluster.'/'. $dt->block.'/'.$dt->nomor;
            $row[] = $dt->cus_name;
            $row[] = '<div class="text-right" style="font-weight:bold">'.number_format($dt->harga_rumah).'</div>';
            $row[] = '<div class="text-right">'.number_format($dt->total_cicilan).'</div>';
            $row[] = $dt->deskripsi;
                      

            $data[]=$row;
        }
        
        return response()->json(["data"=>$data]);
        
    }    
    
    
    function datatermin($id){
        
        $trx = Transaksi::where('rumah_id', $id)->first();
        $dt = Cicilan::where('trans_id', $trx->id)
                        ->get();

        $data = [];
        $no=1;
        $tl=0;
        $tlpct=0;
        
        foreach($dt as $list){
       
            $tl += $list->cicil_nominal;
            $pct = $list->cicil_nominal / $trx->harga_rumah * 100;
            $tlpct += $pct;
            $row = [];
            $row[] = $no++; 
            $row[] = $list->cicil_tgl;
            $row[] = number_format($pct,2);
            $row[] = '<div class="text-right">'.format_uang($list->cicil_nominal).'&nbsp;&nbsp;&nbsp;</div>';
            $row[] = $list->bank_id;
            $row[] = $list->deskripsi;
            
            $data[] = $row;
        }
        $row=[];
        $row[]='';
        $row[]='Sisa';
        $row[]=number_format($tlpct,2);;
        $row[]= '<div class="text-right">'.format_uang($trx->harga_rumah-$tl).'&nbsp;&nbsp;&nbsp;</div>';
        $row[]='';
        $row[]='';
        
        $data[]=$row;
        
        return response()->json(['data'=>$data]);

                        
        
    }
    
}
