<?php

namespace App\Http\Controllers;

use App\Audit;
use App\Komuditi;
use App\KomuditiPurchase;
use App\KomuditiTransaksi;
use App\KomuditiProduk;
use App\Cawangan;
use DB;

use Illuminate\Http\Request;
use Carbon\Carbon;

class KomuditiController extends Controller
{
    public function checkKomuditi(){
        $current = Carbon::now();
        $current = new Carbon();

        $komuditi = KomuditiPurchase::on('mysql7')->where('date_purchase','=',$current->toDateString())->orderBy('created_at','desc')->first();
        return response()->json($komuditi);
    }

    public function checkKomuditiDateChoose(Request $request){
        $current = Carbon::now();
        $current = new Carbon();

        $komuditi = KomuditiPurchase::on('mysql7')->where('date_purchase','=',$request->tarikh)->orderBy('created_at','desc')->first();
        return response()->json($komuditi);
    }

    public function checkKomuditiDashboard(){
        $current = Carbon::now();
        $current = new Carbon();

        $komuditi = KomuditiPurchase::on('mysql7')->select('unit_komuditi')->where('date_purchase','=',$current->toDateString())->orderBy('created_at','desc')->first();

        return response()->json($komuditi['unit_komuditi']);
    }

    public function beliKomuditi(Request $request){
        $current = Carbon::now();

        $komuditi_purchase = KomuditiPurchase::on('mysql7')->create([
            'unit_komuditi' => $request->unit_komuditi,
            'nilai' => $request->nilai,
            'no_sijil' => $request->nosijil,
            'kodproduct' => $request->kodproduct,
            'purchased_by' => $request->purchased_by,
            'date_purchase' => $current->toDateString(),
            'time_purchase' => $current->toTimeString()
        ]);

        $komuditi_history= Komuditi::on('mysql7')->create([
            'unit_komuditi' => $request->unit_komuditi,
            'transaction_by' => $request->purchased_by,
            'date_purchase' => $current->toDateString(),
            'transaction_type' => 'Beli Komoditi',
            'time_purchase' => $current->toTimeString(),
            'nosijil' => $request->nosijil,
            'kodproduk' => $request->kodproduct,
            'harga'=> $request->nilai
        ]);

        $audit = new Audit();
        $audit->users = $request->purchased_by;
        $audit->actions = "pembelian komuditi";
        $audit->new_data = $komuditi_purchase;
        $audit->kodcaw = $request->kodcaw;
        $audit->created_at = $current;
        $audit->updated_at = $current;
        $audit->save();

        return response()->json($komuditi_purchase);
    }

    public function jualKomuditi(Request $request){
        $current = Carbon::now();

        $komuditi_asal = KomuditiPurchase::on('mysql7')->where('no_sijil','=',$request->nosijil)->latest()->first();

        $komuditi_purchase = KomuditiPurchase::on('mysql7')->where('no_sijil','=',$request->nosijil)->update(['unit_komuditi' => 0]);

        $komuditi_history= Komuditi::on('mysql7')->create([
            'unit_komuditi' => $komuditi_asal['unit_komuditi'],
            'transaction_by' => $request->purchased_by,
            'date_purchase' => $current->toDateString(),
            'transaction_type' => 'Jual Komoditi',
            'time_purchase' => $current->toTimeString(),
            'nosijil' => $request->nosijil,
            'kodproduk' => $komuditi_asal['kodproduct'],
            'harga'=> $komuditi_asal['nilai']
        ]);

        $audit = new Audit();
        $audit->users = $request->purchased_by;
        $audit->actions = "penjualan komuditi";
        $audit->new_data = $komuditi_asal;
        $audit->kodcaw = $request->kodcaw;
        $audit->created_at = $current;
        $audit->updated_at = $current;
        $audit->save();
        
        return response()->json('berjaya');
    }

    public function rekodKomuditi(Request $request){
        if(isset($request->limit_view)) {
            $rekodkomuditi = Komuditi::on('mysql7')->orderBy('date_purchase','desc')->orderBy('time_purchase','desc')->limit($request->limit_view)->get();
        } else {
            $rekodkomuditi = Komuditi::on('mysql7')->orderBy('date_purchase','desc')->orderBy('time_purchase','desc')->get();
        }

        return response()->json($rekodkomuditi);
    }

    public function updateKomuditi(Request $request){
        $current = Carbon::now();
        $current = new Carbon();

        $komuditi = KomuditiPurchase::on('mysql7')->where('date_purchase','=',$current->toDateString())->orderBy('created_at','desc')->first();

        $transaksi_asal = KomuditiTransaksi::on('mysql7')->where('norujukan','=',$request->norujukan)->first();
        $unit_baru = $transaksi_asal['unit_komuditi'] - $request->unit_komuditi;
        $unit_current = $komuditi['unit_komuditi'];
        $update_unit = $unit_current + $unit_baru;

        $komuditi_purchase = KomuditiPurchase::on('mysql7')->where('id','=',$komuditi['id'])->update([
            'unit_komuditi' => $update_unit
        ]);

        $komuditi_transaksi = KomuditiTransaksi::on('mysql7')->where('norujukan','=',$request->norujukan)->update([
            'unit_komuditi' => $request->unit_komuditi
        ]);

        return response()->json($komuditi_transaksi);
    }

    public function transaksiKomuditi(Request $request){
        $current = Carbon::now();
        $current = new Carbon();

        $komuditi_current = KomuditiPurchase::on('mysql7')->where('date_purchase','=',$current->toDateString())->orderBy('created_at','desc')->first();

        $unit_current = $komuditi_current['unit_komuditi'];

        $update_unit = $unit_current - $request->unit_komuditi;

        $update_komuditi = KomuditiPurchase::on('mysql7')->where('id','=',$komuditi_current['id'])->update([
            'unit_komuditi' => $update_unit
        ]);

        $komuditi_transaksi = KomuditiTransaksi::on('mysql7')->create([
            'unit_komuditi' => $request->unit_komuditi,
            'nosijil'=>$komuditi_current['no_sijil'],
            'norujukan' => $request->norujukan,
            'kodcaw' => $request->kodcaw ,
            'teller' => $request->teller ,
            'masa' => $current->toTimeString(),
            'tarikh' => $current->toDateString()
        ]);

        return response()->json($komuditi_transaksi);
    }

    public function batalKomuditi(Request $request){

        $komuditi_current = KomuditiPurchase::on('mysql7')->orderBy('created_at','desc')->first();

        $transaksi_asal = KomuditiTransaksi::on('mysql7')->where('norujukan','=',$request->norujukan)->first();

        $unit_current = $komuditi_current['unit_komuditi'];

        $update_unit = $unit_current + $transaksi_asal['unit_komuditi'];

        $update_komuditi = KomuditiPurchase::on('mysql7')->where('id','=',$komuditi_current['id'])->update([
            'unit_komuditi' => $update_unit
        ]);

        $komuditi_transaksi = KomuditiTransaksi::on('mysql7')->where('norujukan','=',$request->norujukan)->delete();

        return response()->json($komuditi_transaksi);
    }

    public function getKomuditiProduct(){
        $produk = KomuditiProduk::on('mysql7')->get();

        return response()->json($produk);
    }

    public function getKomuditiProductUnit(Request $request){
        $produk = KomuditiProduk::on('mysql7')->where('kodproduk','=',$request->kodproduk)->first();

        return response()->json($produk['unit']);
    }

    public function getKomuditiProductDescription(Request $request){
        $produk = KomuditiProduk::on('mysql7')->where('kodproduk','=',$request->kodproduk)->first();

        return response()->json($produk);
    }

    public function rekodTransaksiHarian(){
        $current = Carbon::now();
        $current = new Carbon();

        $komuditi_transaksi = KomuditiTransaksi::on('mysql7')->where('tarikh','=',$current->toDateString())->get();

        return response()->json($komuditi_transaksi);
    }

    public function jumlahKomoditiDashboard(){
        $current = Carbon::now();
        $current = new Carbon();
        $komoditi = [];

        $jumlahkomoditi = Komuditi::on('mysql7')->where([['date_purchase','=',$current->toDateString()], ['transaction_type', '=', 'Beli Komoditi']])->orderBy('created_at','desc')->first();

        $transaksi_komoditi = KomuditiPurchase::on('mysql7')->where('date_purchase','=',$current->toDateString())->orderBy('created_at','desc')->first();

        $baki_komoditi = $jumlahkomoditi['unit_komuditi'] - $transaksi_komoditi['unit_komuditi'];

        $percentage_komoditi_transaksi = ($transaksi_komoditi['unit_komuditi']/$jumlahkomoditi['unit_komuditi'])*100;
        $percentage_baki_komoditi = ($baki_komoditi/$jumlahkomoditi['unit_komuditi'])*100;

        array_push($komoditi,
        ['komoditi_transaksi'=>number_format($transaksi_komoditi['unit_komuditi'],2),
        'baki_komoditi'=>number_format($baki_komoditi,2),
        'percentage_komoditi_transaksi'=>number_format($percentage_komoditi_transaksi,1),
        'percentage_baki_komoditi'=>number_format($percentage_baki_komoditi,1)]);

        return response()->json($komoditi);
    }

    public function statistikKomoditiDashboard(Request $request){
        $current = Carbon::now();
        $current = new Carbon();
        $weekly = Carbon::now();
        $weekly = new Carbon();
        $monthly = Carbon::now();
        $monthly = new Carbon();
        $yearly = Carbon::now();
        $yearly = new Carbon();
        $weekly_array = Carbon::now();
        $weekly_array = new Carbon();
        $monthly_array = Carbon::now();
        $monthly_array = new Carbon();
        $yearly_array = Carbon::now();
        $yearly_array = new Carbon();

        $array_totalup = [];

        if($request->method == 'daily'){
            array_push($array_totalup,['tarikh'=>$current->toDateString(),'totalkomoditi'=>0]);
        }
        if($request->method == 'weekly'){//weekly
            for($i=0;$i<7;$i++){
                if($i == 0){
                    $weekly_array_date = $weekly->subDays(0);
                }else{
                    $weekly_array_date = $weekly->subDays(1);
                }
                array_push($array_totalup,['tarikh'=>$weekly_array_date->toDateString(),'totalkomoditi'=>0]);
            }
        }
        if($request->method == 'monthly'){
            for($i=0;$i<12;$i++){
                if($i == 0){
                    $monthly_array_date = $monthly_array->startOfMonth()->subMonths(0);
                }else{
                    $monthly_array_date = $monthly_array->startOfMonth()->subMonths(1);
                }
                array_push($array_totalup,['tarikh'=>$monthly_array_date->year.'-'.sprintf("%02d", $monthly_array_date->month),'totalkomoditi'=>0]);
            }
        }
        if($request->method == 'yearly'){
            for($i=0;$i<5;$i++){
                if($i == 0){
                    $yearly_array_date = $yearly_array->startOfYear()->subYears(0);
                }else{
                    $yearly_array_date = $yearly_array->startOfYear()->subYears(1);
                }
                array_push($array_totalup,['tarikh'=>sprintf("%04d",$yearly_array_date->year),'totalkomoditi'=>0]);
            }
        }
        $weekly_date = $weekly->subDays(6)->toDateString();
        $monthly_date = $monthly->startOfMonth()->subMonths(11)->toDateString();
        $yearly_date = $yearly->startOfYear()->subYears(4)->toDateString();
        // foreach($cawangan_all as $index => $cawangan){
            if($request->method == 'daily'){
                $pembeliankomuditi = Komuditi::on('mysql7')->selectRaw('SUM(unit_komuditi) as totalkomoditi')->addSelect('date_purchase')->groupBy('date_purchase')
                ->where('date_purchase','=',$current->toDateString())->orderBy('created_at','desc')->get();
            }elseif($request->method == 'weekly')
            {
                $pembeliankomuditi = Komuditi::on('mysql')->selectRaw('SUM(unit_komuditi) as totalkomoditi')->addSelect('date_purchase')->groupBy('date_purchase')
                ->where([['date_purchase','<=',$current->toDateString()],['date_purchase','>=',$weekly_date]])->orderBy('created_at','desc')->get();

            }elseif($request->method == 'monthly')
            {
                $pembeliankomuditi = Komuditi::on('mysql')->selectRaw('SUM(unit_komuditi) AS totalkomoditi')->addSelect(DB::connection('mysql')->raw('DATE_FORMAT(date_purchase, "%Y-%m") as date_purchase'))
                ->groupBy(DB::connection('mysql')->raw("DATE_FORMAT(date_purchase,'%Y%m')"))->where([['date_purchase','<=',$current->toDateString()],['date_purchase','>=',$monthly_date]])
                ->orderBy('created_at','desc')->get();

            }elseif($request->method == 'yearly')
            {
                $pembeliankomuditi = Komuditi::on('mysql')->selectRaw('SUM(unit_komuditi) AS totalkomoditi')->addSelect(DB::connection('mysql')->raw('DATE_FORMAT(date_purchase, "%Y") as date_purchase'))
                ->groupBy(DB::connection('mysql')->raw("DATE_FORMAT(date_purchase,'%Y')"))->where([['date_purchase','<=',$current->toDateString()],['date_purchase','>=',$yearly_date]])
                ->orderBy('created_at','desc')->get();
            }

            foreach($array_totalup as $array_index=>$totalup)
            {
                foreach($pembeliankomuditi as $indextebus=>$pembeliankomuditi_detail){
                    if($totalup['tarikh'] == $pembeliankomuditi_detail['date_purchase']){
                        $jumlahkomoditi = $totalup['totalkomoditi'];
                        $jumlahkomoditi += $pembeliankomuditi_detail['totalkomoditi'];
                        $array_totalup[$array_index]['totalkomoditi'] = $jumlahkomoditi;
                    }
                }
            }


    }

    public function rekodTransaksiKomoditi(Request $request){
        $rekod = KomuditiTransaksi::on('mysql7')->selectRaw('SUM(unit_komuditi) as totalkomoditi')->addSelect('kodcaw','nosijil')->where('tarikh','=',$request->tarikh)->groupBy('kodcaw','nosijil')->get();
        $rekodkomoditi = [];
        foreach($rekod as $index=>$rekodtransaksi){
            $cawangan =Cawangan::on('mysql7')->select('details_caw')->where('kodcaw','=',$rekodtransaksi['kodcaw'])->first();
            array_push($rekodkomoditi,['totalkomoditi'=>$rekodtransaksi['totalkomoditi'],'cawangan'=>$cawangan['details_caw'],'nosijil'=>$rekodtransaksi['nosijil']]);
        }

        return response()->json($rekodkomoditi);
    }

}
