<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\Models\KategoriModel;
use App\Models\ProdukModel;
use App\Models\PembayaranModel;
use App\Models\PengeluaranModel;
use App\Models\PenerimaanModel;
use App\Models\DetailTransaksiPembelianModel;
use App\Models\TransaksiPembelianModel;
use App\Models\TransaksiModel;
use App\Models\JurnalModel;
use App\Models\HutangModel;

use App\Models\Log;
use App\Models\Pengembalian;
use App\Models\DetailPengembalian;

use App\Models\PelangganModel;




use App\Models\User;
use App\Models\SyncModel;
use App\Models\SubDetailTransaksiPembelianModel;
use Illuminate\Support\Str;
use Auth;





use Illuminate\Http\Request;

class KasirApi extends Controller
{


     protected array $sortFields = ['nama_kategori'];


     public function index(Request $request)
          {
            // self::DEFAULT_SORT_FIELD  fungsi ini ada pada Controllers/Controller.php

            $sortFieldInput = $request->input('sort_field', self::DEFAULT_SORT_FIELD);
            $sortField      = in_array($sortFieldInput, $this->sortFields) ? $sortFieldInput : self::DEFAULT_SORT_FIELD;
            $sortOrder      = $request->input('sort_order', self::DEFAULT_SORT_ORDER);
            $query          = KategoriModel::orderBy($sortField, 'desc');
            $perPage        = $request->input('per_page') ?? self::PER_PAGE;
            $searchInput    = $request->input('search');

            if (!is_null($searchInput))
            {
                $searchQuery = "%$searchInput%";
                $query       = $query->where('nama_kategori', 'like', $searchQuery);
            }


            $tgl = date('Y-m-d');



            $absen = $query->paginate((int)$perPage);
            return compact('absen');
          }


          public function produk(Request $request)
          {
            // self::DEFAULT_SORT_FIELD  fungsi ini ada pada Controllers/Controller.php

            $sortFieldInput = $request->input('sort_field', self::DEFAULT_SORT_FIELD);
            $sortField      = in_array($sortFieldInput, $this->sortFields) ? $sortFieldInput : self::DEFAULT_SORT_FIELD;
            $sortOrder      = $request->input('sort_order', self::DEFAULT_SORT_ORDER);
            $query          = ProdukModel::select('id', 'kode','nama_kategori', 'nama_barang', DB::raw('(id_kategori) as id_kategori') , DB::raw('(harga_jual) as harga_jual'), 'harga_grosir', 'harga_beli', 'stok', 'satuan', 'created_at','gambar')->groupBy('id')->orderBy('id', 'desc');
            $perPage        = $request->input('per_page') ?? self::PER_PAGE;
            $searchInput    = $request->input('search');

            if (!is_null($searchInput))
            {
                $searchQuery = "%$searchInput%";
                $query       = $query->where('nama_barang', 'like', $searchQuery);
            }


            $tgl = date('Y-m-d');



            $absen = $query->paginate((int)$perPage);
            return compact('absen');
          }





      public function produkRestore(Request $request)
      {
          // code...
            $cek = ProdukModel::get();
            echo json_encode($cek);
      }

       public function produkSync(Request $request)
      {
          // code...

            $now = date('Y-m-d')." 23:59:59";



          $last = ProdukModel::orderBy('created_at','desc')->limit(1)->first();
          $last_update = date('Y-m-d',strtotime($last->created_at))." 00:00:00";
            $cek = ProdukModel::whereBetween('created_at',[$last_update,$now])->get();
            echo json_encode($cek);
      }



       public function updateProdukSync($kode)
      {
          // code...



         $data = [
                'is_update' => 1
             ];
            $cek = ProdukModel::where('kode', $kode)->update($data);
            echo json_encode($cek);
      }



    public function kategori(Request $request)
    {
            $cek = KategoriModel::get();
            echo json_encode($cek);
    }

    public function penerimaan(Request $request)
    {
           $sortFieldInput = $request->input('sort_field', self::DEFAULT_SORT_FIELD);
            $sortField      = in_array($sortFieldInput, $this->sortFields) ? $sortFieldInput : self::DEFAULT_SORT_FIELD;
            $sortOrder      = $request->input('sort_order', self::DEFAULT_SORT_ORDER);
            $query          = PenerimaanModel::orderBy($sortField, 'desc');
            $perPage        = $request->input('per_page') ?? self::PER_PAGE;
            $searchInput    = $request->input('search');

            if (!is_null($searchInput))
            {
                $searchQuery = "%$searchInput%";
                $query       = $query->where('keterangan', 'like', $searchQuery);
            }






            $penerimaan = $query->paginate((int)$perPage);
            return compact('penerimaan');
    }

    public function pengeluaran(Request $request)
    {
            $sortFieldInput = $request->input('sort_field', self::DEFAULT_SORT_FIELD);
            $sortField      = in_array($sortFieldInput, $this->sortFields) ? $sortFieldInput : self::DEFAULT_SORT_FIELD;
            $sortOrder      = $request->input('sort_order', self::DEFAULT_SORT_ORDER);
            $query          = PengeluaranModel::orderBy($sortField, 'desc');
            $perPage        = $request->input('per_page') ?? self::PER_PAGE;
            $searchInput    = $request->input('search');

            if (!is_null($searchInput))
            {
                $searchQuery = "%$searchInput%";
                $query       = $query->where('keterangan', 'like', $searchQuery);
            }






            $pengeluaran = $query->paginate((int)$perPage);
            return compact('pengeluaran');
    }

      public function profil(Request $request)
    {
            $cek = User::get();
            echo json_encode($cek);
    }

    public function getTanggalTransaksi(Request $request)
    {
            $cek = TransaksiPembelianModel::orderBy('id','desc')->limit(1)->first();
            echo json_encode($cek);
    }






    public function save_sync(Request $request)
      {

             $data = ([
                'id' => $request->id,
                'name' => $request->name,
                'email'=> $request->email,
                'gender'=> $request->gender,
               ]);

             $hasil = SyncModel::create($data);

             echo json_encode($hasil);
      }

      public function save_sync_kategori(Request $request)
      {

             $data = ([
                'id' => $request->id,
                'nama_kategori' => $request->nama_kategori,

               ]);

             $hasil = KategoriModel::create($data);

             echo json_encode($hasil);
      }


      public function show_user()
      {

              $user =  SyncModel::get();

            return  json_encode($user);
      }


      public function show_kategori()
      {

              $kat =  KategoriModel::get();

              return  json_encode($kat);
      }

      public function delete_kategori(Request $request)
      {
              $id = $request->id;

              $del =   KategoriModel::where('id',$id)->delete();

            return  json_encode($del);
      }

       public function delete_produk($id,Request $request)
      {
         // $id = $request->id;

              $del =   DB::table('tb_produk')->where('kode',$id)->delete();

            return  json_encode($del);
      }

      public function delete_penerimaan(Request $request)
      {
           $id = $request->id;

              $del =   DB::table('tb_penerimaan')->where('kode',$id)->delete();

            return  json_encode($del);
      }


      public function delete_pengeluaran(Request $request)
      {
            $id = $request->id;
              $del =   DB::table('tb_pengeluaran')->where('kode',$id)->delete();

            return  json_encode($del);
      }



    public function update_kategori(Request $request)
      {
               $id = $request->id;

               $data = ([
                'nama_kategori' => $request->nama_kategori,
               ]);

               $upd = KategoriModel::where('id', $id)->update($data);


                 if ($upd) {
                        echo json_encode(array("message"=>"Save Success"));
                    }else{
                        echo json_encode(array("message"=>"UPDATE failed"));
                    }
      }


      public function save_detail_trans_pembelian(Request $request,Log $log)
      {
          $idTrans = $request->id_transaksi;

          $ket = $request->ket;

          $nama = ProdukModel::where('kode',$request->id_barang)->first();

          if(!empty($ket)){

               $data = ([
                             //'id_transaksi' => $request->id_transaksi,
                            'id_barang' => $request->id_barang,
                            'nama_barang' => $nama->nama_barang,
                            'harga' => $request->harga,
                            'id_sub_transaksi' => $request->id_sub_transaksi,
                            //'status' => $request->status,
                            'qty' => $request->qty,
                            'catatan' => $request->catatan,
                            'created_at' => $request->created_at,
                           ]);

             $hasil = DetailTransaksiPembelianModel::where('id_transaksi_mobile', $idTrans)->where('id_barang', $request->id_barang)->update($data);
                 echo json_encode($hasil);


                  $logs =[
                     'tanggal'=>now(),
                     'tabel'=> 'tb_detail_transaksi_pembelian',
                     'aksi'=> 'update',
                     'user' => Auth::user()->id,
                     'ip' => $request->ip(),
                     'keterangan' => json_encode($data),
                     'serial' => url('save_detail_trans_pembelian'),
                   ];


                   $log->create($logs);


          }else{

                      if(!empty($idTrans)){
                        $getId =  DetailTransaksiPembelianModel::where('id_transaksi_mobile', $request->id_transaksi)->first();

                           $data = ([
                              'id_transaksi' => $getId->id_transaksi,
                            'id_barang' => $request->id_barang,
                            'nama_barang' => $nama->nama_barang,
                            'id_transaksi_mobile' =>$request->id_transaksi,
                            'id_sub_transaksi' => $request->id_sub_transaksi,
                            'harga' => $request->harga,
                            'diskon' => $request->diskon,
                            'status' => $request->status,
                            'qty' => $request->qty,
                            'catatan' => $request->catatan,
                           'created_at' => $request->created_at,
                           ]);

                         $hasil = DetailTransaksiPembelianModel::create($data);
                          echo json_encode($hasil);


                $logs =[
                     'tanggal'=>now(),
                     'tabel'=> 'tb_detail_transaksi_pembelian',
                     'aksi'=> 'create',
                     'user' => Auth::user()->id,
                     'ip' => $request->ip(),
                     'keterangan' => json_encode($data),
                     'serial' => url('save_detail_trans_pembelian'),
                   ];


                   $log->create($logs);



                      }else{


                          $data = ([
                            'id_barang' => $request->id_barang,
                            'nama_barang' => $nama->nama_barang,
                            'harga' => $request->harga,
                            'diskon' => $request->diskon,
                            'id_sub_transaksi' => $request->id_sub_transaksi,
                            'status' => $request->status,
                            'qty' => $request->qty,
                            'catatan' => $request->catatan,
                            'created_at' => $request->created_at,
                           ]);

                          // DetailTransaksiPembelianModel::where('qty',0)

                         $hasil = DetailTransaksiPembelianModel::create($data);

                         echo json_encode($hasil);

                 $logs =[
                     'tanggal'=>now(),
                     'tabel'=> 'tb_detail_transaksi_pembelian',
                     'aksi'=> 'create',
                     'user' => Auth::user()->id,
                     'ip' => $request->ip(),
                     'keterangan' => json_encode($data),
                     'serial' => url('save_detail_trans_pembelian'),
                   ];


                   $log->create($logs);


                      }
          }
      }


    public function split_trans(Request $request){


    $jumStok = $request->qty - $request->jumlah;
    $harga = $request->harga_jual * $jumStok;

    DetailTransaksiPembelianModel::where('id_transaksi_mobile', $request->id_transaksi)->where('id_barang',$request->id_barang)->update(['qty' => $jumStok, 'harga' => $harga]);

    $nama = ProdukModel::where('kode',$request->id_barang)->first();

       if($request->jumlah != 0)   {
            $data = ([
                            'id_barang' => $request->id_barang,
                            'nama_barang' => $nama->nama_barang,
                            'harga' => $request->harga,
                            'id_sub_transaksi' => $request->id_sub_transaksi,
                            //'diskon' => $request->diskon,
                            'status' => 1,
                            'qty' => $request->jumlah,
                           // 'catatan' => $request->catatan,
                            'created_at' => $request->created_at,
                           ]);

                          // DetailTransaksiPembelianModel::where('qty',0)

                         $hasil = DetailTransaksiPembelianModel::create($data);
       }

       DetailTransaksiPembelianModel::where('qty',0)->delete();
                         echo json_encode('sukses');

      }


    public function split_sub_trans(Request $request){


    $jumStok = $request->qty - $request->jumlah;
    $harga = $request->harga_jual * $jumStok;

    SubDetailTransaksiPembelianModel::where('id_transaksi_mobile', $request->id_transaksi)->where('id_barang',$request->id_barang)->where('id_sub_transaksi',$request->id_sub_transaksi)->update(['qty' => $jumStok, 'harga' => $harga]);

    $nama = ProdukModel::where('id',$request->id_barang)->first();

       if($request->jumlah != 0)   {
            $data = ([
                            'id_barang' => $request->id_barang,
                            'id_sub_transaksi' => $request->id_sub_transaksi,
                            'nama_barang' => $nama->nama_barang,
                            'harga' => $request->harga,
                            'status' => 1,
                            'qty' => $request->jumlah,
                            'created_at' => $request->created_at,
                           ]);
                         $hasil = SubDetailTransaksiPembelianModel::create($data);
       }

       SubDetailTransaksiPembelianModel::where('qty',0)->delete();
                         echo json_encode('sukses');

      }





      public function edit_detail_transaksi_pembelian(Request $request,Log $log){

             $idTrans = $request->id_transaksi;

             $data = ([
                            'id_barang' => $request->id_barang,
                            'harga' => $request->harga,
                            'qty' => $request->qty,
                            'catatan' => $request->catatan,
                            'created_at' => $request->created_at,
                           ]);

             $hasil = DetailTransaksiPembelianModel::where('status', 1)->where('id_barang', $request->id_barang)->update($data);
                 echo json_encode($hasil);

                 $logs =[
                     'tanggal'=>now(),
                     'tabel'=> 'tb_detail_transaksi_pembelian',
                     'aksi'=> 'update',
                     'user' => Auth::user()->id,
                     'ip' => $request->ip(),
                     'keterangan' => json_encode($data),
                     'serial' => url('edit_detail_transaksi_pembelian'),
                   ];


                   $log->create($logs);

      }


      public function delete_detail_transaksi(Request $request,Log $log){
           $id = $request->id_barang;
             $id_sub_transaksi = $request->id_sub_transaksi;

              $del =   DetailTransaksiPembelianModel::where('id_barang',$id)->where('status', 1)->delete();


               SubDetailTransaksiPembelianModel::where('id_sub_transaksi',$id_sub_transaksi)->delete();


               $logs =[
                     'tanggal'=>now(),
                     'tabel'=> 'tb_detail_transaksi_pembelian',
                     'aksi'=> 'delete',
                     'user' => Auth::user()->id,
                     'ip' => $request->ip(),
                     'keterangan' => json_encode($id),
                     'serial' => url('delete_detail_transaksi'),
                   ];


                   $log->create($logs);

            return  json_encode($del);
      }

       public function delete_detail_transaksi_pemesanan(Request $request,Log $log){
           $id_barang = $request->id_barang;
            $id_trx = $request->id_transaksi;


            $data = [

                'id_barang' => $id_barang,

                'id_transaksi' => $id_trx,

                ];

              $del =   DetailTransaksiPembelianModel::where('id_barang',$id_barang)->where('id_transaksi_mobile', $id_trx)->delete();



               $logs =[
                     'tanggal'=>now(),
                     'tabel'=> 'tb_detail_transaksi_pembelian',
                     'aksi'=> 'delete',
                     'user' => Auth::user()->id,
                     'ip' => $request->ip(),
                     'keterangan' => json_encode($data),
                     'serial' => url('delete_detail_transaksi_pemesanan'),
                   ];


                   $log->create($logs);


            return  json_encode($del);
      }

      public function save_transaksi_pembelian_sync(Request $request){





              $trx = TransaksiPembelianModel::create(['id'=> $request->id,'total' => $request->total, 'id_pembeli' => $request->id_pembeli, 'created_at' => $request->created_at]);

            //   DetailTransaksiPembelianModel::where('status', 1)->update([ 'id_transaksi' =>  $trx->id]);
            // DetailTransaksiPembelianModel::where('status', 1)->update([ 'status' => 2]);

             echo json_encode($trx);
      }


      public function save_detail_trans_pembelian_sync(Request $request)
      {


       $nama = ProdukModel::where('kode',$request->id_barang)->first();

              $data = ([
                'id_transaksi' =>  $request->id_transaksi,
                'nama_barang' => $nama->nama_barang,
                'id_barang' => $request->id_barang,
                'harga' => $request->harga,
                'diskon' => $request->diskon,
                'status' => $request->status,
                'qty' => $request->qty,
                'created_at' => date('Y-m-d H:i:s'),
               ]);

             $hasil = DetailTransaksiPembelianModel::create($data);

                $trans = DetailTransaksiPembelianModel::select('tb_detail_transaksi_pembelian.harga', 'tb_detail_transaksi_pembelian.id_barang', 'tb_detail_transaksi_pembelian.qty','tb_detail_transaksi_pembelian.status','tb_detail_transaksi_pembelian.diskon' ,'tb_produk.kode','tb_produk.stok', 'tb_produk.nama_barang','tb_produk.harga_jual')->leftJoin('tb_produk','tb_detail_transaksi_pembelian.id_barang','=','tb_produk.kode')->where('tb_detail_transaksi_pembelian.id_transaksi',$request->id_transaksi)->get();


                 foreach ($trans as $row) {

            $jum_stok = $row->stok - $row->qty;

                DB::table('tb_produk')->where('id',$row->id_barang)->update([ 'stok' => $jum_stok]);
             if($row->qty != 0){
                $this->save_jurnal($row->id_barang,date('Y-m-d H:i:s'),$request->harga,$row->qty,'',1);
             }
           }


             echo json_encode($hasil);
      }


      public function save_jurnal($id_barang, $created_at, $harga,$qty,$keterangan,$status_bayar){



         // $created_at = '2023-14-09 09:20:00';
         // hari Mon, Tue,

          $cekLastData = TransaksiModel::orderBy('id','desc')->first();

          $jam_current = date('H:i:s',strtotime($created_at));

          $hari = date('Y-m-d',strtotime($cekLastData->tgl_trans));


          $hari2 = date('Y-m-d',strtotime($created_at));

          $originalDate;
          $untilDate;

         $jam = DB::table('tb_jam_kerja')->where('pilih',1)->first();


          $jam_masuk = date('H:i:s',strtotime($jam->jam_masuk));
          $jam_pulang = date('H:i:s',strtotime($jam->jam_pulang));

    if ($jam_current >= '00:00:00' && $jam_current < $jam_pulang) {

        if($hari == $hari2 && ($jam_current >= $jam_masuk && $jam_current < '00:00:00'  )){

          $originalDate = date('Y-m-d '.$jam_masuk,strtotime($created_at));

          $untilDate = date('Y-m-d '.$jam_pulang,strtotime("+1 day", strtotime( $created_at)));
        }else if(($hari == $hari2) && ($jam_current >= '00:00:00' && $jam_current < $jam_pulang  )){

              $originalDate = date('Y-m-d '.$jam_masuk,strtotime("-1 day",strtotime($created_at)));

          $untilDate = date('Y-m-d '.$jam_pulang,strtotime($created_at));

        }else if(($hari != $hari2)  && ($jam_current > '00:00:00' && $jam_current < $jam_pulang  )){

          $originalDate = date('Y-m-d '.$jam_masuk,strtotime("-1 day",strtotime($created_at)));

          $untilDate = date('Y-m-d '.$jam_pulang,strtotime($created_at));

        }else{

            $originalDate = date('Y-m-d '.$jam_masuk,strtotime($created_at));

          $untilDate = date('Y-m-d '.$jam_pulang,strtotime("+1 day", strtotime( $created_at)));

        }

    }else{


          $originalDate = date('Y-m-d '.$jam_masuk,strtotime($created_at));

          $untilDate = date('Y-m-d '.$jam_pulang,strtotime("+1 day", strtotime( $created_at)));


    }




          $cekDay = TransaksiModel::whereRaw("tgl_trans between '$originalDate' and '$untilDate'")->first();




          $id_user = Auth::user()->id;



          if(empty($cekDay->id)){

            $cekSebelumData = TransaksiModel::orderBy('id','desc')->first();

            if($cekSebelumData->saldo == 0){
                $this->cekSaldo($cekSebelumData->tgl_trans);
            }

               $cekSebelumDataNew = TransaksiModel::orderBy('id','desc')->first();


             TransaksiModel::create([
                'tgl_trans' =>$cekSebelumDataNew->tgl_trans,
                'kode' => 'Saldo Akhir',
                'keterangan' => 'Saldo Akhir',
                'jumlah' => $cekSebelumDataNew->saldo,
                'debet' =>   0,
                'kredit' => 0,
                'saldo' => $cekSebelumDataNew->saldo,
                'user_id' => $id_user,
                'isLock' => 1,
                'isClosing' => 0,
                'status_bayar' => $status_bayar,
            ]);



            TransaksiModel::create([
                'tgl_trans' => $created_at,
                'kode' => 'Saldo Awal',
                'keterangan' => 'Saldo Awal',
                'jumlah' => $cekSebelumDataNew->saldo,
                'debet' =>   0,
                'kredit' => 0,
                'saldo' => $cekSebelumDataNew->saldo,
                'user_id' => $id_user,
                'isLock' => 0,
                'isClosing' => 0,
                'status_bayar' => $status_bayar,
            ]);
          }



                $prod = DB::table('tb_produk')->where('kode',$id_barang)->first();

            $ket = !empty($keterangan) ?  $keterangan : $prod->nama_barang;

                $cek = TransaksiModel::create([
                    'tgl_trans' => $created_at,
                    'kode' => $id_barang,
                    'jumlah' => $harga,
                    'debet' => $harga,
                    'keterangan' =>   $ket,
                    'kredit' => 0,
                    'user_id' => $id_user,
                    'qty' => $qty,
                    'saldo' => 0,
                     'isClosing' => 0,
                     'isLock' => 0,
                    'status_bayar' => $status_bayar,
                ]);

      }

      public function cekKode(Request $request){
          $kode = $request->kode;

          $cek = ProdukModel::where('kode',$kode)->first();

          if(empty($cek->id)){
              $this->add_produk_mobile();
             //echo json_encode('kosong');
          }else{

              echo json_encode('ada');
          }

      }


      public function save_pembayaran_sync(Request $request){



               $data = ([
                'total' => $request->total,
                'id_transaksi' => $request->id_transaksi,
                'dibayar' => $request->dibayar,
                'kembalian' => $request->kembalian,

               ]);

             $hasil = PembayaranModel::create($data);

               echo json_encode($hasil);
      }




      public function save_pembayaran(Request $request,Log $log)
      {
                $total_hutang = $request->total_hutang;



                $trx = TransaksiPembelianModel::create(['total' => $request->total, 'id_pembeli' => $request->id_pembeli,'status_bayar'=> $request->status_bayar, 'created_at' => $request->created_at,'id_pelanggan' => $request->id_pelanggan,'total_hutang'=>$request->total_hutang
                    ,'total_bayar'=>$request->total_bayar,'sisa_hutang'=>$request->sisa_hutang]);


              $data = ([
                'total' => $request->total,
                'id_transaksi' => $trx->id,
                'dibayar' => $request->dibayar,
                'kembalian' => $request->kembalian,

               ]);

             $hasil = PembayaranModel::create($data);

        if($total_hutang != '' || !empty($total_hutang)){

            DetailTransaksiPembelianModel::where('status', 1)->update([ 'id_transaksi' =>  $trx->id]);

            DetailTransaksiPembelianModel::where('status', 1)->update([ 'status' => 5,'id_transaksi_mobile' => $request->id_transaksi]);

           
        }else{

            DetailTransaksiPembelianModel::where('status', 1)->update([ 'id_transaksi' =>  $trx->id]);
            DetailTransaksiPembelianModel::where('status', 1)->update([ 'status' => 2,'id_transaksi_mobile' => $request->id_transaksi]);

            SubDetailTransaksiPembelianModel::where('status', 1)->update([ 'id_transaksi' =>  $trx->id]);
            SubDetailTransaksiPembelianModel::where('status', 1)->update([ 'status' => 2,'id_transaksi_mobile' => $request->id_transaksi]);           
        }

        $dataHutang = [

            'id_transaksi' => $trx->id,
            'id_transaksi_mobile' => $request->id_transaksi,
            'total_hutang'=>$request->total_hutang,
            'total_bayar'=>$request->total_bayar,
            'sisa_hutang'=>$request->sisa_hutang
        ];

          DB::table('tb_hutang')->insert($dataHutang);


           $trans = DetailTransaksiPembelianModel::select('tb_detail_transaksi_pembelian.harga',
           'tb_detail_transaksi_pembelian.created_at',
           'tb_detail_transaksi_pembelian.id_barang', 'tb_detail_transaksi_pembelian.qty','tb_detail_transaksi_pembelian.status','tb_detail_transaksi_pembelian.diskon'
           ,'tb_produk.kode','tb_produk.stok', 'tb_produk.nama_barang','tb_produk.harga_jual')->leftJoin('tb_produk','tb_detail_transaksi_pembelian.id_barang','=','tb_produk.kode')
           ->where('tb_detail_transaksi_pembelian.id_transaksi',$trx->id)->get();

            $subTrans = DB::table('tb_sub_detail_transaksi_pembelian as a')->select('a.harga',
           'a.created_at',
           'a.id_barang', 'a.qty','a.status','a.diskon'
           ,'b.kode','b.stok', 'b.nama_barang','b.harga_jual')->leftJoin('tb_produk as b','a.id_barang','=','b.kode')
           ->where('a.id_transaksi',$trx->id)->get();





           foreach ($trans as $row) {

            $jum_stok = $row->stok - $row->qty;

            $data_stok = [

                'stok' =>$jum_stok,
                'kode' => $row->id_barang,

                ];

                DB::table('tb_produk')->where('kode',$row->id_barang)->update([ 'stok' => $jum_stok]);
                     if($row->qty != 0){
                        //$this->save_jurnal($row->id_barang,$request->created_at,$row->harga,$row->qty,'',$request->status_bayar);
                     }



                 $logs =[
                     'tanggal'=>now(),
                     'tabel'=> 'tb_produk',
                     'aksi'=> 'update',
                     'user' => Auth::user()->id,
                     'ip' => $request->ip(),
                     'keterangan' => json_encode($data_stok),
                     'serial' => url('save_pembayaran'),
                   ];


                   $log->create($logs);

           }


            foreach ($subTrans as $row) {

            $jum_stok = $row->stok - $row->qty;

                DB::table('tb_produk')->where('kode',$row->id_barang)->update([ 'stok' => $jum_stok]);
                     if($row->qty != 0){
                       // $this->save_jurnal($row->id_barang,$request->created_at,$row->harga,$row->qty,'',$request->status_bayar);
                     }


            $data_stok = [

                'stok' =>$jum_stok,
                'kode' => $row->id_barang,

                ];




                 $logs =[
                     'tanggal'=>now(),
                     'tabel'=> 'tb_produk',
                     'aksi'=> 'update',
                     'user' => Auth::user()->id,
                     'ip' => $request->ip(),
                     'keterangan' => json_encode($data_stok),
                     'serial' => url('save_pembayaran'),
                   ];


                   $log->create($logs);

           }

             echo json_encode($hasil);
      }



      public function save_pemesanan_didepan(Request $request)
      {

                $trx = TransaksiPembelianModel::create(['total' => $request->total, 'id_pembeli' => $request->id_pembeli, 'status_bayar' =>  $request->status_bayar,'created_at' => $request->created_at]);






            SubDetailTransaksiPembelianModel::where('status', 1)->update([ 'id_transaksi' =>  $trx->id]);
            SubDetailTransaksiPembelianModel::where('status', 1)->update([ 'status' => 3,'id_transaksi_mobile' => $request->id_transaksi]);


            DetailTransaksiPembelianModel::where('status', 1)->update([ 'id_transaksi' =>  $trx->id]);
            DetailTransaksiPembelianModel::where('status', 1)->update([ 'status' => 3,'id_transaksi_mobile' => $request->id_transaksi]);



             echo json_encode('sukses');
      }

      public function save_pembayaran_didepan(Request $request)
      {
             $trans = DetailTransaksiPembelianModel::select('tb_detail_transaksi_pembelian.harga', 'tb_detail_transaksi_pembelian.id_barang', 'tb_detail_transaksi_pembelian.qty',
             'tb_detail_transaksi_pembelian.status','tb_detail_transaksi_pembelian.diskon' ,'tb_produk.kode','tb_produk.stok', 'tb_produk.nama_barang','tb_produk.harga_jual')
             ->leftJoin('tb_produk','tb_detail_transaksi_pembelian.id_barang','=','tb_produk.kode')
             ->where('tb_detail_transaksi_pembelian.id_transaksi_mobile',$request->id_transaksi)->get();

              $subTrans = DB::table('tb_sub_detail_transaksi_pembelian as a')->select('a.harga',
                           'a.created_at',
                           'a.id_barang', 'a.qty','a.status','a.diskon'
                           ,'b.kode','b.stok', 'b.nama_barang','b.harga_jual')->leftJoin('tb_produk as b','a.id_barang','=','b.kode')
                           ->where('a.id_transaksi_mobile',$request->id_transaksi)->get();

               $data = ([
                'total' => $request->total,
                'id_transaksi' => $request->id_transaksi,
                'dibayar' => $request->dibayar,
                'kembalian' => $request->kembalian,

               ]);

             $hasil = PembayaranModel::create($data);

               DetailTransaksiPembelianModel::where('id_transaksi_mobile', $request->id_transaksi)->update([ 'status' => 2]);
               SubDetailTransaksiPembelianModel::where('id_transaksi_mobile', $request->id_transaksi)->update([ 'status' => 2]);




          foreach ($trans as $row) {

            $jum_stok = $row->stok - $row->qty;

                DB::table('tb_produk')->where('kode',$row->id_barang)->update([ 'stok' => $jum_stok]);

               if($row->qty != 0){
                 //$this->save_jurnal($row->id_barang,$request->created_at,$row->harga,$row->qty,'',1);
               }

          }

          foreach ($subTrans as $row) {

            $jum_stok = $row->stok - $row->qty;

                DB::table('tb_produk')->where('kode',$row->id_barang)->update([ 'stok' => $jum_stok]);

               if($row->qty != 0){
                // $this->save_jurnal($row->id_barang,$request->created_at,$row->harga,$row->qty,'',1);
               }

          }

             echo json_encode('sukses');

      }



      public function add_produk(Request $request)
      {




                        $arrValid = array(
                         'image'=>'mimes:jpg,jpeg,png|max:2000',
                        );

               $request->validate(
                            $arrValid,
                            array(
                                                 'image.max' => 'File lebih dari 2MB',
                                                 'image.mimes' => 'Minimal JPG, JPEG, PNG',
                            )
                        );
                        $image = $request->file('image');

                        if ($request->file('image') != null) {



                            $imageName = 'profile_pengguna_'.Str::random(5).'.'.$image->extension();


                             $request->file('image')->move(public_path().'/images/', $imageName);



                                   $data = ([
                                    'kode' => $request->kode,
                                    'nama_barang' => $request->nama_barang,
                                    'id_kategori' => $request->id_kategori,
                                    'harga_jual' => $request->harga_jual,
                                    'harga_grosir' => $request->harga_grosir,
                                    'harga_beli' => $request->harga_beli,
                                    'stok' => $request->stok,
                                    'satuan' => $request->satuan,
                                    'gambar' =>  asset('images/'.$imageName),
                                    'created_at' => date('Y-m-d H:i'),

                                   ]);

                                   $cek = DB::table('tb_produk')->insert($data);



                                 if ($cek){
                                        echo json_encode(array("message"=>"Save Success"));
                                    }else{
                                        echo json_encode(array("message"=>"SAVE failed"));
                                    }
                        }else{

                        $idProd =     ProdukModel::orderBy('id','desc')->limit(1)->first();

                        $add;
                        if(empty($idProd->id)){
                            $add =  1;  
                        }else{
                          $add =  $idProd->id + 1;
                        }
  


                         $num_padded = sprintf("%05d", $add);

                                 $data = ([
                                    'kode' => $num_padded,
                                    'nama_barang' => $request->nama_barang,
                                    'id_kategori' => $request->id_kategori,
                                    'harga_jual' => $request->harga_jual,
                                    //'harga_grosir' => $request->harga_grosir,
                                    'harga_beli' => $request->harga_beli,
                                    'stok' => $request->stok,
                                    //'satuan' => $request->satuan,
                                    //'gambar' =>  asset('images/'.$imageName),
                                    'created_at' => date('Y-m-d H:i'),

                                   ]);

                                   $cek = DB::table('tb_produk')->insert($data);



                                 if ($cek){
                                        echo json_encode(array("message"=>"Save Success"));
                                    }else{
                                        echo json_encode(array("message"=>"SAVE failed"));
                                    }

                        }





      }

      public function add_produk_mobile(Request $request,Log $log)
      {


               if($request->id != 0) {

                    $image = $request->image;


                             $image = $request->image;

                          $imageName = 'profile_pengguna_'.Str::random(5).'-'.$image;
                             $realImage = base64_decode($request->base);


                              file_put_contents(public_path().'/images/'.$imageName,$realImage);



                   if (!empty($request->image)) {

                    $id = $request->id;

                     $kode = $request->kode;

                     $data = ([
                    'kode' => $request->kode,
                    'nama_barang' => $request->nama_barang,
                    'id_kategori' => $request->id_kategori,
                    'harga_jual' => $request->harga_jual,
                    'harga_grosir' => $request->harga_grosir,
                    'harga_beli' => $request->harga_beli,
                    'stok' => $request->stok,
                    'satuan' => $request->satuan,
                    'gambar' =>  asset('images/'.$imageName),
                    'created_at' => $request->created_at,
                    'harga_shopee_food' => $request->shopee_food,
                    'harga_go_food' => $request->go_food,
                    'keterangan' => $request->keterangan,


                   ]);

                   $upd = DB::table('tb_produk')->where('kode', $kode)->update($data);

                    if ($upd){
                        echo json_encode(array("message"=>"Save Success"));
                    }else{
                        echo json_encode(array("message"=>"SAVE failed"));
                    }

                    $logs =[
                     'tanggal'=>now(),
                     'tabel'=> 'tb_produk',
                     'aksi'=> 'update',
                     'user' => Auth::user()->id,
                     'ip' => $request->ip(),
                     'keterangan' => json_encode($data),
                     'serial' => url('add_produk_mobile'),
                   ];


                   $log->create($logs);

                   }else{
                        $kode = $request->kode;
                        $data = ([
                    'kode' => $request->kode,
                    'nama_barang' => $request->nama_barang,
                    'id_kategori' => $request->id_kategori,
                    'harga_jual' => $request->harga_jual,
                   // 'harga_grosir' => $request->harga_grosir,
                    'harga_beli' => $request->harga_beli,
                    'stok' => $request->stok,
                    //'satuan' => $request->satuan,
                   // 'gambar' =>  asset('images/'.$imageName),
                    'created_at' => $request->created_at,
                    'harga_shopee_food' => $request->shopee_food,
                    'harga_go_food' => $request->go_food,
                    'keterangan' => $request->keterangan,

                   ]);

                   $upd = DB::table('tb_produk')->where('kode', $kode)->update($data);

                     if ($upd){
                        echo json_encode(array("message"=>"Save Success"));
                    }else{
                        echo json_encode(array("message"=>"SAVE failed"));
                    }

                     $logs =[
                     'tanggal'=>now(),
                     'tabel'=> 'tb_produk',
                     'aksi'=> 'update',
                     'user' => Auth::user()->id,
                     'ip' => $request->ip(),
                     'keterangan' => json_encode($data),
                     'serial' => url('add_produk_mobile'),
                   ];


                   $log->create($logs);


                   }






               }else{

                  // $image = $request->image;

                  if(!empty($request->image)){
                             $image = $request->image;

                          $imageName = 'profile_pengguna_'.Str::random(5).'.'.$image;
                             $realImage = base64_decode($request->base);


                              file_put_contents(public_path().'/images/'.$imageName,$realImage);

                                   $data = ([
                                    'kode' => $request->kode,
                                    'nama_barang' => $request->nama_barang,
                                    'id_kategori' => $request->id_kategori,
                                    'harga_jual' => $request->harga_jual,
                                    'harga_grosir' => $request->harga_grosir,
                                    'harga_beli' => $request->harga_beli,
                                    'stok' => $request->stok,
                                     'satuan' => $request->satuan,
                                    'gambar' =>  asset('images/'.$imageName),
                                    'created_at' => $request->created_at,
                                    'harga_shopee_food' => $request->shopee_food,
                                     'harga_go_food' => $request->go_food,
                                     'keterangan' => $request->keterangan,

                                   ]);

                                   $cek = DB::table('tb_produk')->insert($data);


                                 if ($cek){
                                        echo json_encode(array("message"=>"Save Success"));
                                    }else{
                                        echo json_encode(array("message"=>"SAVE failed"));
                                    }

                                     $logs =[
                                         'tanggal'=>now(),
                                         'tabel'=> 'tb_produk',
                                         'aksi'=> 'create',
                                         'user' => Auth::user()->id,
                                         'ip' => $request->ip(),
                                         'keterangan' => json_encode($data),
                                         'serial' => url('add_produk_mobile'),
                                       ];


                                       $log->create($logs);

                  }else{


                             $data = ([
                                    'kode' => $request->kode,
                                    'nama_barang' => $request->nama_barang,
                                    'id_kategori' => $request->id_kategori,
                                    'harga_jual' => $request->harga_jual,
                                    //'harga_grosir' => $request->harga_grosir,
                                    'harga_beli' => $request->harga_beli,
                                    'stok' => $request->stok,
                                    //'satuan' => $request->satuan,

                                    'created_at' => $request->created_at,
                                    'harga_shopee_food' => $request->shopee_food,
                                    'harga_go_food' => $request->go_food,
                                    'keterangan' => $request->keterangan,

                                   ]);

                                   $cek = DB::table('tb_produk')->insert($data);


                                 if ($cek){
                                        echo json_encode(array("message"=>"Save Success"));
                                    }else{
                                        echo json_encode(array("message"=>"SAVE failed"));
                                    }

                                    $logs =[
                                     'tanggal'=>now(),
                                     'tabel'=> 'tb_produk',
                                     'aksi'=> 'create',
                                     'user' => Auth::user()->id,
                                     'ip' => $request->ip(),
                                     'keterangan' => json_encode($data),
                                     'serial' => url('add_produk_mobile'),
                                   ];


                                   $log->create($logs);

                  }

                }



      }


      public function update_produk_mobile(Request $request)
      {


                        $image = $request->image;

                        $id = $request->id;

                        if ($request->image) {
                             $image = $request->image;

                          $imageName = 'profile_pengguna_'.Str::random(5).'.'.$image;
                             $realImage = base64_decode($request->base);


                             file_put_contents(public_path().'/images/'.$imageName,$realImage);

                                   $data = ([
                                    'kode' => $request->kode,
                                    'nama_barang' => $request->nama_barang,
                                    'id_kategori' => $request->id_kategori,
                                    'harga_jual' => $request->harga_jual,
                                    'harga_grosir' => $request->harga_grosir,
                                    'harga_beli' => $request->harga_beli,
                                    'stok' => $request->stok,
                                    'satuan' => $request->satuan,
                                    'gambar' =>  asset('images/'.$imageName),
                                    'created_at' => $request->created_at,
                                    'keterangan' => $request->keterangan,

                                   ]);

                                   $upd = DB::table('tb_produk')->where('id', $id)->update($data);


                                 if ($upd){
                                        echo json_encode(array("message"=>"Save Success"));
                                    }else{
                                        echo json_encode(array("message"=>"SAVE failed"));
                                    }
                    }else{


                            $data = ([
                                    'kode' => $request->kode,
                                    'nama_barang' => $request->nama_barang,
                                    'id_kategori' => $request->id_kategori,
                                    'harga_jual' => $request->harga_jual,
                                    //'harga_grosir' => $request->harga_grosir,
                                    'harga_beli' => $request->harga_beli,
                                    'stok' => $request->stok,
                                    //'satuan' => $request->satuan,
                                    //'gambar' =>  asset('images/'.$imageName),
                                    'created_at' => $request->created_at,
                                    'keterangan' => $request->keterangan,

                                   ]);

                                   $upd = DB::table('tb_produk')->where('id', $id)->update($data);


                                 if ($upd){
                                        echo json_encode(array("message"=>"Save Success"));
                                    }else{
                                        echo json_encode(array("message"=>"SAVE failed"));
                                    }
                    }
      }

      public function update_produk(Request $request)
      {

            $arrValid = array(
                         'image'=>'mimes:jpg,jpeg,png|max:2000',
                        );

               $request->validate(
                            $arrValid,
                            array(
                                                 'image.max' => 'File lebih dari 2MB',
                                                 'image.mimes' => 'Minimal JPG, JPEG, PNG',
                            )
                        );
                        $image = $request->file('image');

                        $imageName = '';

                                    if ($request->file('image') != null) {

                                        $imageName = 'profile_pengguna_'.Str::random(5).'.'.$image->extension();


                                        $request->file('image')->move(public_path().'/images/', $imageName);

                                         $id = $request->id;


                                     $data = ([
                                                'kode' => $request->kode,
                                                'nama_barang' => $request->nama_barang,
                                                'id_kategori' => $request->id_kategori,
                                                'harga_jual' => $request->harga_jual,
                                                'harga_grosir' => $request->harga_grosir,
                                                'harga_beli' => $request->harga_beli,
                                                'stok' => $request->stok,
                                                'satuan' => $request->satuan,
                                                 'gambar' =>  asset('images/'.$imageName),
                                                 'created_at' => date('Y-m-d H:i'),
                                                 'keterangan' => $request->keterangan,
                                               ]);


                                $upd = DB::table('tb_produk')->where('id', $id)->update($data);

                             if ($upd) {
                                    echo json_encode(array("message"=>"Save Success"));
                                }else{
                                    echo json_encode(array("message"=>"UPDATE failed"));
                                }


                        }else{

                                 $id = $request->id;


                                     $data = ([
                                                'kode' => $request->kode,
                                                'nama_barang' => $request->nama_barang,
                                                'id_kategori' => $request->id_kategori,
                                                'harga_jual' => $request->harga_jual,
                                                'harga_grosir' => $request->harga_grosir,
                                                'harga_beli' => $request->harga_beli,
                                                'stok' => $request->stok,
                                                'satuan' => $request->satuan,
                                                'created_at' => date('Y-m-d H:i'),
                                                'keterangan' => $request->keterangan,

                                                // 'gambar' =>  asset('storage/images/'.$imageName),
                                              ]);


                                $upd = DB::table('tb_produk')->where('id', $id)->update($data);

                             if ($upd) {
                                    echo json_encode(array("message"=>"Save Success"));
                                }else{
                                    echo json_encode(array("message"=>"UPDATE failed"));
                                }


                        }


      }


    public function add_kategori(Request $request)
      {

               $data = ([
                'nama_kategori' => $request->nama_kategori,
               ]);

               $upd = KategoriModel::create($data);



                 if ($upd) {
                        echo json_encode(array("message"=>"Save Success"));
                    }else{
                        echo json_encode(array("message"=>"SAVE failed"));
                    }
      }





    public function save_kategori(Request $request)
    {

        $cek = DB::table('tb_kategori')->where('nama_kategori', $request->nama_kategori)->first();

        if(!empty($cek->id)){

              $simpan = KategoriModel::create([
                                            'nama_kategori' => $request->nama_kategori,
                                         ]);


                    if ($simpan) {
                        echo json_encode(array("message"=>"Save Success"));
                    }else{
                        echo json_encode(array("message"=>"UPDATE failed"));
                    }

        }else{

                 $simpan = KategoriModel::create([
                                            'nama_kategori' => $request->nama_kategori,

                                         ]);

                    if ($simpan) {
                        echo json_encode(array("message"=>"Save Success"));
                    }else{
                        echo json_encode(array("message"=>"UPDATE failed"));
                    }


        }

    }

    public function laporan_today($tanggal,$status,Request $request)
      {
          // code... laba
      

        $mulai = date('Y-m-d',strtotime($tanggal)).' 00:00:00';
        $selesai = date('Y-m-d', strtotime($tanggal)).' 23:59:59';






        $satuQuery = DB::table('tb_transaksi_pembelian as a')
        ->leftJoin('tb_detail_transaksi_pembelian as b', 'b.id_transaksi', '=', 'a.id')
        ->leftJoin('tb_produk as c', 'c.kode', '=', 'b.id_barang')
        ->where('b.status', 2)
        ->whereBetween('b.created_at', [$mulai,$selesai])
        ->select(DB::raw('SUM((c.harga_jual - c.harga_beli) * b.qty) as harga','status_bayar'));

         if($status != 0){

                 $satuQuery->where('status_bayar',$status );
            }

    // Query kedua
    $duaQuery = DB::table('tb_transaksi_pembelian as a')
        ->leftJoin('tb_sub_detail_transaksi_pembelian as b', 'b.id_transaksi', '=', 'a.id')
        ->leftJoin('tb_produk as c', 'c.kode', '=', 'b.id_barang')
        ->where('b.status', 2)
        ->whereBetween('b.created_at', [$mulai,$selesai])
        ->select(DB::raw('SUM((c.harga_jual - c.harga_beli) * b.qty) as harga','status_bayar'));

         if($status != 0){

                 $duaQuery->where('status_bayar',$status );
            }


    // Gabungkan kedua query dengan UNION ALL
    $gabungQuery = $satuQuery->unionAll($duaQuery);

    // Bungkus query gabungan dalam subquery untuk menghitung total harga
    $query = DB::table(DB::raw("({$gabungQuery->toSql()}) as TotalAll"))
        ->mergeBindings($gabungQuery) // Menggabungkan bindings untuk parameter
        ->select(DB::raw('SUM(harga) as total'));



            $laba = $query->first();





         $result_laba =    !empty($laba->total) ? $laba->total : 0;

         $result_laba_format =  number_format($result_laba);
          

            $firstQuery = DB::table('tb_sub_detail_transaksi_pembelian as a')
                    ->leftJoin('tb_transaksi_pembelian as c', 'c.id', '=', 'a.id_transaksi')
                    ->select(DB::raw('SUM(a.harga) as harga_1'), 'a.status', 'c.status_bayar', 'a.created_at')
                    ->where('a.status', 2)
                     ->whereBetween('c.created_at',[$mulai,$selesai]);


               if($status != 0){

                 $firstQuery->where('status_bayar',$status );
                }

                // Query kedua
                $secondQuery = DB::table('tb_detail_transaksi_pembelian as b')
                    ->leftJoin('tb_transaksi_pembelian as c', 'c.id', '=', 'b.id_transaksi')
                    ->select(DB::raw('SUM(b.harga) as harga_1'), 'b.status', 'c.status_bayar', 'b.created_at')
                    ->where('b.status', 2)
                     ->whereBetween('c.created_at',[$mulai,$selesai]);


               if($status != 0){

                 $secondQuery->where('status_bayar',$status );
                }

                // Gabungkan kedua query dengan UNION ALL
                $unionQuery = $firstQuery->unionAll($secondQuery);

                // Bungkus query gabungan dalam subquery untuk menghitung total harga
                $query2 = DB::table(DB::raw("({$unionQuery->toSql()}) as TotalAll"))
                    ->mergeBindings($unionQuery) // Menggabungkan bindings untuk parameter
                    ->select(DB::raw('SUM(harga_1) as tot_harga'));



                 $omset = $query2->first();


             $result_omset =    !empty($omset->tot_harga) ? $omset->tot_harga : 0;
             $result_omset_format = number_format($result_omset);



            // select sum(nilai) as tot, keterangan, created_at from tb_penerimaan where created_at between '$mulaiNow' and '$selesaiNow'

            $pemasukan =  DB::table('tb_penerimaan')->select(DB::raw('sum(nilai) as tot'))->whereBetween('created_at',[$mulai,$selesai])->first();

            $result_masuk =    !empty($pemasukan->tot) ? $pemasukan->tot : 0;

            $result_masuk_format = number_format($result_masuk);

            // "select sum(nilai) as tot, keterangan, created_at from tb_pengeluaran where created_at between '$mulaiNow' and '$selesaiNow'");

             $pengeluaran =  DB::table('tb_pengeluaran')->select(DB::raw('sum(nilai) as tot'))->whereBetween('created_at',[$mulai,$selesai])->first();

            $result_keluar =    !empty($pengeluaran->tot) ? $pengeluaran->tot : 0;

            $result_keluar_format = number_format($result_keluar);


               // labaBersihTot = untung! + uangTerima - uangKeluar;

            //allIncome = untung! + uangTerima;

             $laba_bersih_tot = ($result_laba + $result_masuk) - $result_keluar;

             $laba_bersih_tot_format = number_format($laba_bersih_tot);

             $all_income = $result_laba  + $result_masuk;

             $all_income_format = number_format($all_income);


             return compact('result_omset_format','result_laba_format','result_masuk_format','result_keluar_format','laba_bersih_tot_format','all_income_format');


      }


       public function penerimaanPengeluaranLaporan($tanggal,Request $request)
      {
          // code...

           $mulai = date('Y-m-d',strtotime($tanggal)).' 00:00:00';
        $selesai = date('Y-m-d', strtotime($tanggal)).' 23:59:59';

        //      $mulai = date('Y-m-d 09:00:00',strtotime($tanggal));
        // $selesai = date('Y-m-d 05:00:00',strtotime("+1 day", strtotime($tanggal)));

            $penerimaan = PenerimaanModel::whereBetween('created_at',[$mulai,$selesai])->get();

            $pengeluaran = PengeluaranModel::whereBetween('created_at',[$mulai,$selesai])->get();
            return compact('penerimaan','pengeluaran');
      }


        public function list_laporan_today($tanggal,$status,Request $request)
      {
          // code...
 //SUM(( harga_jual) * qty ) as total
        DB::table('tb_produk')->whereRaw('nama_barang is null')->delete();


        // $mulai = date('Y-m-d 09:00:00',strtotime($tanggal));
        // $selesai = date('Y-m-d 05:00:00',strtotime("+1 day", strtotime($tanggal)));

         $mulai = date('Y-m-d',strtotime($tanggal)).' 00:00:00';
        $selesai = date('Y-m-d', strtotime($tanggal)).' 23:59:59';

        //   $untilDate = date('Y-m-d 05:00:00',strtotime("+1 day", strtotime( $created_at)));

// id_barang disandingkan dengan kode barang karena yang disimpan waktu save transaksi pembelian adalah kode barangnya bukan idnya


        $firstQuery = DB::table('tb_transaksi_pembelian as d')
        ->leftJoin('tb_detail_transaksi_pembelian as a', 'a.id_transaksi', '=', 'd.id')
        ->leftJoin('tb_produk as b', 'a.id_barang', '=', 'b.kode')
        ->whereBetween('a.created_at', [$mulai,$selesai])
        ->where('a.status', 2)
        ->groupBy('a.id_transaksi')
         ->groupBy('a.id_barang')
        ->select(
            'b.kode',
            'a.id_barang',
            'b.nama_barang',
            'd.created_at',
            'status_bayar',
            DB::raw('MAX(b.harga_jual) as harga_jual'),
            DB::raw('SUM(a.qty) as qty'),
            DB::raw('SUM((b.harga_jual - b.harga_beli) * a.qty) as laba'),
            DB::raw('SUM(b.harga_jual * a.qty) as total')
        );

         if($status != 0){

                     $firstQuery->where('status_bayar',$status );
             }


// Query kedua
        $secondQuery = DB::table('tb_transaksi_pembelian as d')
            ->leftJoin('tb_sub_detail_transaksi_pembelian as a', 'a.id_transaksi', '=', 'd.id')
            ->leftJoin('tb_produk as b', 'a.id_barang', '=', 'b.kode')
            ->whereBetween('a.created_at', [$mulai,$selesai])
            ->where('a.status', 2)
            ->groupBy('a.id_sub_transaksi')
             ->groupBy('a.id_barang')
            ->select(
                'b.kode',
                'a.id_barang',
                'b.nama_barang',
                'd.created_at',
                'status_bayar',
                DB::raw('MAX(b.harga_jual) as harga_jual'),
                DB::raw('SUM(a.qty) as qty'),
                DB::raw('SUM((b.harga_jual - b.harga_beli) * a.qty) as laba'),
                DB::raw('SUM(b.harga_jual * a.qty) as total')
            );

             if($status != 0){

                     $secondQuery->where('status_bayar',$status );
             }


        // Gabungkan kedua query dengan UNION ALL
        $unionQuery = $firstQuery->unionAll($secondQuery);

        // Eksekusi query dan ambil hasilnya
        $results = DB::table(DB::raw("({$unionQuery->toSql()}) as unioned"))
            ->mergeBindings($unionQuery);


            $det = $results->orderBy('created_at','desc')->get();

           // return compact('det');

             echo json_encode($det);


      }

      public function penerimaanPengeluaranLaporanBulanan($bulan,Request $request)
      {
          // code...

            $month = date('m',strtotime($bulan));
           $year = date('Y',strtotime($bulan));

            $penerimaan = PenerimaanModel::select(DB::raw('max(id) as id'),DB::raw('sum(nilai) as nilai'),DB::raw('date(created_at) as tanggal'))->where(DB::raw('month(created_at)'), $month)
             ->where(DB::raw('year(created_at)'), $year)
             ->groupBy(DB::raw("DATE(created_at)"))->get();

            $pengeluaran = PengeluaranModel::select(DB::raw('max(id) as id'),DB::raw('sum(nilai) as nilai'),DB::raw('date(created_at) as tanggal'))->where(DB::raw('month(created_at)'), $month)
             ->where(DB::raw('year(created_at)'), $year)
             ->groupBy(DB::raw("DATE(created_at)"))->get();
            return compact('penerimaan','pengeluaran');
      }


      public function list_laporan_bulanan($bulan,$status,Request $request)
      {


           $month = date('m',strtotime($bulan));
           $year = date('Y',strtotime($bulan));




        $query = DB::table('tb_transaksi_pembelian as d')
                    ->select(DB::raw('DATE(a.created_at) as tanggal'),
                    DB::raw('SUM((b.harga_jual - b.harga_beli) * a.qty) as laba'),
                    DB::raw('SUM((b.harga_jual) * a.qty) as omset'),'d.created_at')
                    ->leftJoin('tb_detail_transaksi_pembelian as a', 'a.id_transaksi', '=', 'd.id')
                    ->leftJoin('tb_produk as b', 'a.id_barang', '=', 'b.kode')
                    ->whereMonth('a.created_at', $month)
                    ->whereYear('a.created_at', $year)
                    ->where('a.status', 2)
                    ->groupBy(DB::raw('DATE(a.created_at)'))
                    ->unionAll(
                DB::table('tb_transaksi_pembelian as d')
                  ->select(DB::raw('DATE(a.created_at) as tanggal'),
                    DB::raw('SUM((b.harga_jual - b.harga_beli) * a.qty) as laba'),
                    DB::raw('SUM((b.harga_jual) * a.qty) as omset'),'d.created_at')
                ->leftJoin('tb_sub_detail_transaksi_pembelian as a', 'a.id_transaksi', '=', 'd.id')
                ->leftJoin('tb_produk as b', 'a.id_barang', '=', 'b.kode')
                ->whereMonth('a.created_at', $month)
                ->whereYear('a.created_at', $year)
                ->where('a.status', 2)
                ->groupBy(DB::raw('DATE(a.created_at)'))
                    );

             if($status != 0){

                     $query->where('status_bayar',$status );
             }

          $det =  $query->groupBy(DB::raw("DATE(a.created_at)"))->orderBy('created_at','desc')->get();


             echo json_encode($det);


      }


    public function laporan_bulanan($bulan,$status)
    {
        // code...


         $month = date('m',strtotime($bulan));

         $year = date('Y',strtotime($bulan));

         $query = TransaksiPembelianModel::select(DB::raw('SUM(( harga_jual - harga_beli) * qty ) as total'))
            ->leftJoin('tb_detail_transaksi_pembelian', 'tb_detail_transaksi_pembelian.id_transaksi','=','tb_transaksi_pembelian.id')
            ->leftJoin('tb_produk','tb_produk.kode','=','tb_detail_transaksi_pembelian.id_barang')
            ->where(  DB::raw('month(tb_detail_transaksi_pembelian.created_at)'), $month)
            ->where('status',2)
             ->where(  DB::raw('year(tb_detail_transaksi_pembelian.created_at)'), $year);

              if($status != 0){

                     $query->where('status_bayar',$status );
              }

          $laba =  $query->first();

         $result_laba =    !empty($laba->total) ? $laba->total : 0;



            $query2 = DetailTransaksiPembelianModel::select(DB::raw('sum(harga) as tot_harga'))->from('tb_detail_transaksi_pembelian as a')->leftJoin('tb_produk as b','a.id_barang','=','b.kode')->leftJoin('tb_transaksi_pembelian as c','c.id','=','a.id_transaksi')
                ->where(  DB::raw('month(c.created_at)'), $month)
                ->where('status',2)
                ->where(  DB::raw('year(c.created_at)'), $year);

                if($status != 0){

                     $query2->where('status_bayar',$status );
                }


              $omset = $query2->first();

             $result_omset =    !empty($omset->tot_harga) ? $omset->tot_harga : 0;




               $pemasukan =  DB::table('tb_penerimaan')->select(DB::raw('sum(nilai) as tot'))
                ->where(  DB::raw('month(tb_penerimaan.created_at)'), $month)
                ->where(  DB::raw('year(tb_penerimaan.created_at)'), $year)->first();

            $result_masuk =    !empty($pemasukan->tot) ? $pemasukan->tot : 0;

            $pengeluaran =  DB::table('tb_pengeluaran')->select(DB::raw('sum(nilai) as tot'))
                ->where(  DB::raw('month(tb_pengeluaran.created_at)'), $month)
                ->where(  DB::raw('year(tb_pengeluaran.created_at)'), $year)->first();

            $result_keluar =    !empty($pengeluaran->tot) ? $pengeluaran->tot : 0;


             $laba_bersih_tot = ($result_laba + $result_masuk) - $result_keluar;

             $all_income = $result_laba  + $result_masuk;



              return compact('result_omset','result_laba','result_masuk','result_keluar','laba_bersih_tot','all_income');


    }

     public function laporan_tahunan($tahun,$status)
    {
        // code...


         $month = date('m',strtotime($tahun));

           $year = date('Y',strtotime($tahun));

         $query = TransaksiPembelianModel::select(DB::raw('SUM(( harga_jual - harga_beli) * qty ) as total'))
            ->leftJoin('tb_detail_transaksi_pembelian', 'tb_detail_transaksi_pembelian.id_transaksi','=','tb_transaksi_pembelian.id')
            ->leftJoin('tb_produk','tb_produk.kode','=','tb_detail_transaksi_pembelian.id_barang')
            ->where('status',2)
             ->where(  DB::raw('year(tb_detail_transaksi_pembelian.created_at)'), $year);

               if($status != 0){

                     $query->where('status_bayar',$status );
                }

          $laba =   $query->first();

         $result_laba =    !empty($laba->total) ? $laba->total : 0;



            $query2 = DetailTransaksiPembelianModel::select(DB::raw('sum(harga) as tot_harga'))->from('tb_detail_transaksi_pembelian as a')->leftJoin('tb_produk as b','a.id_barang','=','b.kode')->leftJoin('tb_transaksi_pembelian as c','c.id','=','a.id_transaksi')
            ->where('status',2)
                ->where(  DB::raw('year(c.created_at)'), $year);


                if($status != 0){

                     $query2->where('status_bayar',$status );
                }

            $omset =    $query2->first();

             $result_omset =    !empty($omset->tot_harga) ? $omset->tot_harga : 0;




               $pemasukan =  DB::table('tb_penerimaan')->select(DB::raw('sum(nilai) as tot'))
                ->where(  DB::raw('year(tb_penerimaan.created_at)'), $year)->first();

            $result_masuk =    !empty($pemasukan->tot) ? $pemasukan->tot : 0;

            $pengeluaran =  DB::table('tb_pengeluaran')->select(DB::raw('sum(nilai) as tot'))
                ->where(  DB::raw('year(tb_pengeluaran.created_at)'), $year)->first();

            $result_keluar =    !empty($pengeluaran->tot) ? $pengeluaran->tot : 0;


             $laba_bersih_tot = ($result_laba + $result_masuk) - $result_keluar;

             $all_income = $result_laba  + $result_masuk;



              return compact('result_omset','result_laba','result_masuk','result_keluar','laba_bersih_tot','all_income');


    }



    public function list_laporan_tahunan($tahun,$status,Request $request)
      {

           $year = date('Y',strtotime($tahun));


         $query =   TransaksiPembelianModel::from('tb_transaksi_pembelian as d')->select(
            DB::raw("month(a.created_at) as bulan"),
            DB::raw('SUM(( harga_jual - harga_beli) * qty ) as laba'),
            DB::raw('SUM(( harga_jual) * qty ) as omset'))
            ->leftJoin('tb_detail_transaksi_pembelian as a','a.id_transaksi','=','d.id')
            ->leftJoin('tb_produk as b','a.id_barang','=','b.kode')
             ->where(  DB::raw('year(a.created_at)'), $year)
             ->where('status',2);

              if($status != 0){

                     $query->where('status_bayar',$status );
                }
           $det =  $query->groupBy(DB::raw("month(a.created_at)"))->get();


             echo json_encode($det);


      }


      public function penerimaanPengeluaranLaporanTahunan($tahun,Request $request)
      {
          // code...


           $year = date('Y',strtotime($tahun));

            $penerimaan = PenerimaanModel::select(DB::raw('max(id) as id'),DB::raw('sum(nilai) as nilai'),DB::raw('month(created_at) as bulan'))
             ->where(DB::raw('year(created_at)'), $year)
             ->groupBy(DB::raw("month(created_at)"))
             ->orderBy(DB::raw("month(created_at)"),'asc')->get();

            $pengeluaran = PengeluaranModel::select(DB::raw('max(id) as id'),DB::raw('sum(nilai) as nilai'),DB::raw('month(created_at) as bulan'))
             ->where(DB::raw('year(created_at)'), $year)
             ->groupBy(DB::raw("month(created_at)"))
             ->orderBy(DB::raw("month(created_at)"),'asc')->get();
            return compact('penerimaan','pengeluaran');
      }

    public function createPengeluaran(Request $request)
    {
            $peng = PengeluaranModel::create([
                'nilai' => $request->nilai,
                'keterangan' => $request->keterangan,
                'kode' => $request->id,

            ]);
               
                    if($peng){
                        echo json_encode(array("message"=>"Save Success"));
                    }else{
                        echo json_encode(array("message"=>"SAVE failed"));
                    }
    }


    public function createPenerimaan(Request $request)
    {
            $pen = PenerimaanModel::create([
                'nilai' => $request->nilai,
                'keterangan' => $request->keterangan,
                'kode' => $request->id,
            ]);



                    if($pen){
                        echo json_encode(array("message"=>"Save Success"));
                    }else{
                        echo json_encode(array("message"=>"SAVE failed"));
                    }
    }

    public function laporan_admin($tanggal)
    {



              $mulai = date('Y-m-d',strtotime($tanggal)).' 00:00:00';
              $selesai = date('Y-m-d', strtotime($tanggal)).' 23:59:59';

               $out = PengeluaranModel::select('nilai')->whereBetween('created_at',[$mulai,$selesai])->first();
               $keluar = !empty($out->nilai) ? $out->nilai : 0;


               $in  = PenerimaanModel::select('nilai')->whereBetween('created_at',[$mulai,$selesai])->first();
               $masuk = !empty($in->nilai) ? $in->nilai : 0;

               $saldo = $masuk - $keluar;



               return compact('keluar','masuk','saldo');

    }

    public function penjualan_terbanyak($bulan)
    {
        // SELECT  b.id_barang,   sum(qty), harga_jual FROM tb_transaksi_pembelian a LEFT JOIN tb_detail_transaksi_pembelian  b on a.id = b.id_transaksi left join tb_produk c on c.id = b.id_barang  WHERE  month(b.created_at) = 07 group by id_barang order by sum(qty) desc;

        $month = date('m',strtotime($bulan));
        $year = date('Y',strtotime($bulan));


         $det =  DetailTransaksiPembelianModel::select('nama_barang','b.id_barang','gambar',DB::raw('sum(qty) as jumlah'), 'harga_jual',)
                                       ->from('tb_detail_transaksi_pembelian as b')
                                       ->leftJoin('tb_produk as c','c.kode','=','b.id_barang')
                                       ->where(DB::raw('month(b.created_at)'), $month)
                                       ->where(DB::raw('year(b.created_at)'), $year)
                                       ->where('status',2)
                                       ->groupBy('id_barang')
                                       ->orderBy(DB::raw('sum(qty)'),'desc')->get();

        echo json_encode($det);
    }


    public function last_produk_id(){

        $row =    ProdukModel::orderBy('id','desc')->limit(1)->first();

        $add =  $row->id + 1;

        $num_padded = sprintf("%05d", $add);
        //echo $num_padded;

        echo json_encode($num_padded);



    }

    public function logout(Request $res)
    {


       auth()->logout();
      return response()->json([
          'success'    => true,
          'message' => 'Logout successfully'
      ]);
     }

     public function truncate_produk(Request $req)
    {

      DB::table('tb_produk')->truncate();


      return response()->json([
          'success'    => true,
        //   'message' => 'Logout successfully'
      ]);
     }


     public function truncate_pemesanan(Request $req)
    {

       TransaksiPembelianModel::truncate();
       DetailTransaksiPembelianModel::truncate();
       SubDetailTransaksiPembelianModel::truncate();
       PembayaranModel::truncate();
       TransaksiModel::truncate();
       HutangModel::truncate();

      return response()->json([
          'success'    => true,
        //   'message' => 'Logout successfully'
      ]);
     }


       public function truncate_in_out(Request $req)
    {

       PenerimaanModel::truncate();

       PengeluaranModel::truncate();

      return response()->json([
          'success'    => true,
        //   'message' => 'Logout successfully'
      ]);
     }



    public function transaksiJurnal($tanggal,$status)
    {

        $now = date('Y-m-d',strtotime($tanggal));

        $id_user = Auth::user()->id;

        $query =  JurnalModel::whereRaw("date(tgl_trans) = '$now' and keterangan != 'Saldo Akhir' ");
              if($status != 0){
                     $query->where('status_bayar',$status );
              }
        $trans = $query->get();

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

    public function totTransaksi($tanggal,$status){

         $now = date('Y-m-d',strtotime($tanggal));


           $q_total = JurnalModel::whereRaw("date(tgl_trans) = '$now' and keterangan != 'Saldo Akhir' ")->orderBy('id','desc');

           if($status != 0){
                         $q_total->where('status_bayar',$status );
            }

          $total =   $q_total->first();







          $tot = !empty($total->saldo) ? number_format($total->saldo) : 0;
          $q_totAll = JurnalModel::whereRaw("date(tgl_trans) = '$now'")->select(DB::raw('sum(debet) as debet'),DB::raw('sum(kredit) as kredit'));

          if($status != 0){
                         $q_totAll->where('status_bayar',$status );
            }

          $totAll = $q_totAll->first();

          $debet = number_format($totAll->debet);
          $kredit = number_format($totAll->kredit);


          return compact('tot','debet','kredit');

    }


    public function cekSaldo($tanggal)
    {

          $now = date('Y-m-d',strtotime($tanggal));

TransaksiModel::whereRaw("debet = 0 and kredit = 0 and saldo =0")->delete();


     $cekTanggal = JurnalModel::whereRaw("date(tgl_trans) = '$now'")->first();
       $x = 0;



        if(empty($cekTanggal->id)){
              $akun = TransaksiModel::whereRaw("isLock != 1")->orderBy('id','asc')->get();


                  foreach ($akun as $key) {
                    $x++;
                           $after = TransaksiModel::whereRaw("isLock = 1")->orderBy('id','desc')->limit(1)->first();
                           $last = TransaksiModel::where('id',$key->id)->first();

                  //  if(!empty($after->id)){

                          if($last->debet > 0 ){
                            $hasil =  $last->jumlah + $after->saldo;

                            // echo "<pre>";
                            // print_r($last->jumlah.' + '.$after->saldo);
                            //  echo "</pre>";
                            TransaksiModel::where('id',$last->id)->update(['saldo' => $hasil,'isLock' => 1 ]);
                          }

                          if($last->kredit > 0 ){
                              $hasil =   $after->saldo -  $last->jumlah;
                              TransaksiModel::where('id',$last->id)->update([ 'saldo' => $hasil,'isLock' => 1 ]);
                          }




                  } // end foreach


        }else{

              $akun = TransaksiModel::whereRaw("isLock != 1")->orderBy('id','asc')->get();

                foreach ($akun as $key) {
               $x++;
                   $after = TransaksiModel::whereRaw("isLock = 1")->orderBy('id','desc')->first();
                   $last = TransaksiModel::where('id',$key->id)->first();



                  if($last->debet > 0 ){

                    $hasil =  $last->jumlah + $after->saldo;

                    TransaksiModel::where('id',$last->id)->update([ 'saldo' => $hasil,'isLock' => 1 ]);
                  }

                  if($last->kredit > 0 ){
                      $hasil =   $after->saldo -  $last->jumlah;

                      TransaksiModel::where('id',$last->id)->update([ 'saldo' => $hasil,'isLock' => 1 ]);
                  } // end if




            }//end foreach



        }   // end of if

        TransaksiModel::whereRaw("isLock != 1")->update(['isLock' => 1]);



        $jurnal = TransaksiModel::whereRaw("isClosing != 1 or isClosing is null")->get();

         // JurnalModel::whereRaw("date(tgl_trans) = '$now'")->delete();

                  foreach ($jurnal as $key) {

                     if($key->kredit > 0 ){
                                $cek = JurnalModel::create([
                                    'tgl_trans' => $key->tgl_trans,
                                    'kode' => $key->kode,
                                    'keterangan' => $key->keterangan,
                                    'jumlah' => $key->jumlah,
                                    'debet' => 0,
                                    'kredit' => $key->jumlah,
                                    'user_id' =>  $key->user_id,
                                    'qty' =>  $key->qty,
                                    'saldo' =>  $key->saldo,
                                    'status_bayar' =>  $key->status_bayar,
                                    'isLock' =>  1,
                                    'isClosing' =>  1,

                                ]);
                            } else {

                                $cek = JurnalModel::create([
                                    'tgl_trans' => $key->tgl_trans,
                                    'kode' => $key->kode,
                                    'keterangan' => $key->keterangan,
                                    'jumlah' => $key->jumlah,
                                    'debet' => $key->jumlah,
                                    'kredit' => 0,
                                    'user_id' =>  $key->user_id,
                                     'qty' =>  $key->qty,
                                    'saldo' =>  $key->saldo,
                                    'status_bayar' =>  $key->status_bayar,
                                    'isLock' =>  1,
                                    'isClosing' =>  1,
                                ]);


                            }// end if

                  } // end foreach

                  TransaksiModel::whereRaw("isClosing != 1  or isClosing is null")->update(['isClosing' => 1]);
            $lastJurnal = JurnalModel::orderBy('id','desc')->first();

            JurnalModel::create([
                'tgl_trans' => $lastJurnal->tgl_trans,
                'kode' => 'Saldo Akhir',
                'keterangan' => 'Saldo Akhir',
                'jumlah' => $lastJurnal->saldo,
                'debet' =>   0,
                'kredit' => 0,
                'saldo' => $lastJurnal->saldo,
                'user_id' => $lastJurnal->user_id,
                'isLock' => 1,
                'isClosing' => 1,
                'status_bayar' => $lastJurnal->status_bayar,
            ]);

            echo json_encode('sukses');
    }


    public function transaksiJurnalPerBulan($tanggal)
    {

        $bulan = date('m',strtotime($tanggal));

         $tahun = date('Y',strtotime($tanggal));

        $id_user = Auth::user()->id;

        $query =  JurnalModel::select(DB::raw('date(tgl_trans) as tanggal'),'saldo')->whereRaw("month(tgl_trans) = $bulan and year(tgl_trans) = $tahun")->where('keterangan','Saldo Akhir')->groupBy(DB::raw('date(tgl_trans)'))->orderBy('tgl_trans','asc');

        $trans = $query->get();

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


    public function update_penerimaan(Request $request){

        $id = $request->id;

        PenerimaanModel::where('kode',$id)->update(['nilai' => $request->nilai, 'keterangan' => $request->keterangan]);

         $cek = TransaksiModel::where('id_penerimaan',$id)->update([
                    'tgl_trans' =>date('Y-m-d H:i:s'),
                    'jumlah' => $request->nilai,
                    'debet' => $request->nilai,
                    'keterangan' =>   $request->keterangan,




                ]);


        return response()->json('Sukses');
    }


    public function update_pengeluaran(Request $request){

        $id = $request->id;

        PengeluaranModel::where('kode',$id)->update(['nilai' => $request->nilai, 'keterangan' => $request->keterangan]);

          $cek = TransaksiModel::where('id_pengeluaran',$id)->update([
                    'tgl_trans' =>date('Y-m-d H:i:s'),
                    'jumlah' => $request->nilai,
                    'kredit' => $request->nilai,
                    'keterangan' =>   $request->keterangan,
                ]);

        return response()->json('Sukses');
    }


    public function jam_kerja(){

        $jaker = DB::table('tb_jam_kerja')->get();

        return response()->json($jaker);

    }


    public function update_jam_kerja(Request $request){

        $id = $request->id_mobile;

        $jaker = DB::table('tb_jam_kerja')->where('id_mobile',$id)->update(['jam_masuk' => $request->jam_masuk, 'jam_pulang' => $request->jam_pulang,'id_hari_mulai' => $request->id_hari_mulai, 'id_hari_selesai' => $request->id_hari_selesai]);

        return response()->json('sukses');

    }

     public function tambah_jam_kerja(Request $request){

        $add = DB::table('tb_jam_kerja')->insert([
               'nama' => $request->nama,
               'jam_masuk' => $request->jam_masuk,
               'jam_pulang' => $request->jam_pulang,
               'id_mobile' => $request->id_mobile,
               'id_hari_mulai' => $request->id_hari_mulai,
               'id_hari_selesai' => $request->id_hari_selesai,
            ]);

        return response()->json('sukses');

    }


    public function ubahHarga(Request $request, Log $log){

        $harga =  $request->harga;
        $idBarang =  $request->id_barang;

        $data = [
            'harga' => $harga,
            'id_barang' => $idBarang,

            ];


       // "update tb_detail_transaksi_pembelian set harga = '$harga' where id_barang = '$idBarang' and status = 1");

        DB::table('tb_detail_transaksi_pembelian')->where('id_barang',$idBarang)->where('status',1)->update(['harga' => $harga]);

            $logs =[
                     'tanggal'=>now(),
                     'tabel'=> 'tb_detail_transaksi_pembelian',
                     'aksi'=> 'create',
                     'user' => Auth::user()->id,
                     'ip' => $request->ip(),
                     'keterangan' => json_encode($data),
                     'serial' => url('ubahHarga'),
                   ];


                   $log->create($logs);


    }

     public function simpanSubDetail(Request $request,Log $log){

          $add = SubDetailTransaksiPembelianModel::create([
               'id_sub_transaksi' => $request->id_sub_transaksi,
               'id_barang' => $request->id_barang,
               'harga' => $request->harga,
               'status' => 1,
               'qty' => $request->qty,
               'created_at' => date('Y-m-d H:i:s')

            ]);

        return response()->json('sukses');

        $logs =[
                     'tanggal'=>now(),
                     'tabel'=> 'tb_sub_detail_transaksi_pembelian',
                     'aksi'=> 'update',
                     'user' => Auth::user()->id,
                     'ip' => $request->ip(),
                     'keterangan' => json_encode($add),
                     'serial' => url('simpanSubDetail'),
                   ];


                   $log->create($logs);

     }

      public function pengembalian(Request $request, Log $log)
     {
         // code...

        DB::beginTransaction();

                try {


                DetailTransaksiPembelianModel::where('id_barang', $request->id_barang)->where('id_transaksi_mobile', $request->id_transaksi)->update(['status' => 4]);


                $trans = DetailTransaksiPembelianModel::where('id_barang', $request->id_barang)->where('id_transaksi_mobile', $request->id_transaksi)->first();

                      

                     $pengembalian = Pengembalian::create([
                            'kode' => 'RET-' . date('Ymd') . '-' . rand(100, 999),
                            'id_transaksi' => $request->id_transaksi,
                            'id_pelanggan' => $request->id_pelanggan,
                            'total' => $trans->harga,
                            'keterangan' => $request->keterangan,
                            
                        ]);

                  

                   //  dd($trans->produk);


                        // 3. Simpan detail barang yang dikembalikan
                       
                            DetailPengembalian::create([
                                'id_pengembalian' => $pengembalian->id,
                                'id_barang' => $request->id_barang,
                                'jumlah' =>  $trans->qty,
                                'harga' =>  $trans->produk->harga,
                                'sub_total' => $trans->harga,
                             
                            ]);
                            $stok = $trans->produk->stok + $request->qty;

                            DB::table('tb_produk')->where('id',$request->id_barang)->update([ 'stok' => $stok ]);
                        

                    DB::commit();

                    return response()->json([
                        'status' => true,
                        'message' => 'Pengembalian berhasil disimpan.',
                        'data' => $pengembalian
                    ]);

                } catch (\Exception $e) {
                    DB::rollBack();

                    return response()->json([
                        'status' => false,
                        'message' => 'Terjadi kesalahan: ' . $e->getMessage(),
                ], 500);

            }

        }

        public function pelanggan(Request $request){

            $data = PelangganModel::get();

            echo json_encode($data);

        }

        public function simpanPelanggan(Request $request,Log $log)
        {
            $validated = $request->validate([
                'nama' => 'required|string|max:100',
                'no_hp' => 'nullable|string|max:20',
                'alamat' => 'nullable|string',
                'kode' => 'nullable|string',
            ]);

            $pelanggan = PelangganModel::create($validated);


                 $logs =[
                         'tanggal'=>now(),
                         'tabel'=> 'pelanggan',
                         'aksi'=> 'create',
                         'user' => Auth::user()->id,
                         'ip' => $request->ip(),
                         'keterangan' => json_encode($validated),
                         'serial' => url('simpanPelanggan'),
                       ];


                 $log->create($logs);

            return response()->json(['message' => 'Pelanggan berhasil ditambahkan', 'data' => $pelanggan], 201);
        }

        // Update
        public function updatePelanggan(Request $request, Log $log)
        {

            $kode = $request->kode;

            $validated = $request->validate([
                'nama' => 'required|string|max:100',
                'no_hp' => 'nullable|string|max:20',
                'alamat' => 'nullable|string',
                'kode' => 'nullable|string',

            ]);

             PelangganModel::where('kode',$kode)->update($validated);

               $logs =[
                         'tanggal'=>now(),
                         'tabel'=> 'pelanggan',
                         'aksi'=> 'update',
                         'user' => Auth::user()->id,
                         'ip' => $request->ip(),
                         'keterangan' => json_encode($validated),
                         'serial' => url('updatePelanggan'),
                       ];


                   $log->create($logs);


            return response()->json(['message' => 'Pelanggan berhasil diupdate'],201);
        }

        // Delete
        public function destroyPelanggan(Request $request)
        {
            $kode = $request->kode;
            $pelanggan = PelangganModel::where('kode',$kode)->delete();
            

            return response()->json(['message' => 'Pelanggan berhasil dihapus'],201);
        }


        public function save_hutang(Request $request)
        {

            $last = HutangModel::where('id_transaksi_mobile', $request->id_transaksi_mobile)->orderBy('id','desc')->first();

            $data = [
                'id_transaksi' => $last->id_transaksi,
                'id_transaksi_mobile' => $request->id_transaksi_mobile,
                'total_bayar' => $request->total_bayar,
                'sisa_hutang' => $request->sisa_hutang,
                'total_hutang' => $request->total_hutang,
            ];

            TransaksiPembelianModel::where('id', $last->id_transaksi)->update([ 'total_bayar' => $request->total_bayar,
                'sisa_hutang' => $request->sisa_hutang,
                'total_hutang' => $request->total_hutang ]);

            HutangModel::create($data);



    $total_bayar = HutangModel::select(DB::raw('sum(total_bayar) as total_bayar'))->where('id_transaksi_mobile', $request->id_transaksi_mobile)->first();

            HutangModel::where('id',$last->id_transaksi)->update([ 'total_bayar' => $total_bayar->total_bayar, 'sisa_hutang' => $request->sisa_hutang]);

            return response()->json(['message' => 'sukses'],200);




        }

   












}
