<?php

namespace App\Http\Controllers;

use App\Bank;
use App\Gadai;
use App\Cawangan;
use App\KelantanPayPayment;
use Illuminate\Http\Request;

class KelantanPayController extends Controller
{
    public function index(Request $request){
        $norujukan = $request->sag;

        $kodcaw = substr($norujukan,0,strlen($norujukan)-11);

        $cawangan = Cawangan::on('mysql7')->where('kodcaw',$kodcaw)->first();

        $gadaiData = Gadai::on($cawangan['mysql'])->where([['norujukan',$norujukan],['nokp',$request->nokp]])->first();

        if($gadaiData){
            $tenpercent = $gadaiData['nilaimarhun'] * 0.1;
            $maxbayaran = $gadaiData['bakipjm'] - $tenpercent + $this->kiraupahTawarruq($kodcaw,$norujukan);
            $gadai = [
                'nosag'             =>  $gadaiData['norujukan'],
                'pinjaman'          =>  $gadaiData['pinjaman'],
                'bakipinjaman'      =>  $gadaiData['bakipjm'],
                'hargajualan'       =>  $gadaiData['hargajualan'],
                'bakihargajualan'   =>  $gadaiData['bakihargajualan'],
                'tempohgadai'       =>  $gadaiData['tempoh'],
                'tempohkeuntungan'  =>  $gadaiData['tempoh']-$gadaiData['tempohbayar'],
                'koskeuntungan'     =>  $this->kiraupahTawarruq($kodcaw,$norujukan),
                'maxbayaran'        =>  $maxbayaran,
            ];

            return response()->json($gadai);
        }else{
            return response()->json('Gadaian Tidak Wujud');
        }
    }

    public function kiraupahTawarruq($kodcaw,$norujukan){
        $cawangan = Cawangan::on('mysql7')
                    ->where('kodcaw','=',$kodcaw)
                    ->first();

        $gadai_data = Gadai::on($cawangan['mysql'])
                    ->where('norujukan','=',$norujukan)
                    ->first();

        $bilang_bln = $gadai_data['tempoh'] - $gadai_data['tempohbayar'];

        $upahsemasa_raw = $bilang_bln * (($gadai_data['kadarupah']/100 )* $gadai_data['pinjaman']);

        $upah_semasa_round = number_format($upahsemasa_raw,2);
        $upah_semasa = substr($upah_semasa_round, 0, -1);
	    $upah_semasa = floatval(preg_replace('/[^\d.]/', '', $upah_semasa));
        return $upah_semasa;
    }

    public function postPayment(Request $request){
        $payment = new KelantanPayPayment();
        $payment->norujukan = $request->sag;
        $payment->nokp = $request->nokp;
        $payment->kp_reference_no = $request->reference_no;
        $payment->payment_date = $request->payment_date;
        $payment->payment_time = $request->payment_time;
        $payment->status = 1;
        $payment->cron_update = 0;

        $payment->save();
    }
}