<?php

namespace App\Http\Controllers;

use App\Models\Karyawan;
use App\Models\Keranjang;
use App\Models\Kurir;
use App\Models\Member;
use App\Models\Ongkirmember;
use App\Models\Pembayaran;
use App\Models\Poinbelanja;
use App\Models\Produk;
use App\Models\Transaksi;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Mike42\Escpos\PrintConnectors\FilePrintConnector;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
use Mike42\Escpos\Printer;

class TransaksiController extends Controller
{
    public function index()
    {
        $karyawan = Karyawan::latest()->get();
        $data = [
            'title' => 'Ramizah Store | Transaksi',
            'page' => 'Transaksi',
            'menuActive' => 'transaksi',
            'menuOpen' => 'transaksi',
        ];
        return view('kasir.transaksi.transaksi', compact('data', 'karyawan'));
    }

    public function simpan_keranjang(Request $request)
    {
        $p = Produk::where('kd_produk', $request->kode)->first();
        $m = Member::where('kd_member', '0')->first();

        $cek = Transaksi::where('user_id', Auth::user()->id)->where('sts_transaksi', 'Y')->count();

        $cek_stok = stok($p->id) - terjual($p->id);

        if (!empty($cek_stok)) {

            if (empty($cek)) {
                $id = Transaksi::create([
                    'user_id' => Auth::user()->id,
                    'member_id' => $m->id,
                    'kd_transaksi' => kodetransaksi(),
                    'jumlah' => 0,
                    'ongkir' => 0,
                    'diskon' => 0,
                    'total' => 0,
                    'dibayar' => 0,
                    'sts_transaksi' => 'Y',
                    'via_bayar' => 'K',
                    'jns_transaksi' => 'OFF',
                    'sts_antar' => 'N',
                    'ip_address' => getClientIP(),
                ])->id;

                Keranjang::create([
                    'transaksi_id' => $id,
                    'produk_id' => $p->id,
                    'berat' => $p->berat,
                    'harga' => $p->harga_jual,
                    'jumlah' => 1,
                    'diskon' => $p->diskon,
                ]);
            } else {
                $t = Transaksi::where('user_id', Auth::user()->id)->where('sts_transaksi', 'Y')->first();

                $k = Keranjang::where('transaksi_id', $t->id)->where('produk_id', $p->id)->first();
                if (empty($k->id)) {
                    Keranjang::create([
                        'transaksi_id' => $t->id,
                        'produk_id' => $p->id,
                        'berat' => $p->berat,
                        'harga' => $p->harga_jual,
                        'jumlah' => 1,
                        'diskon' => $p->diskon,
                    ]);
                } else {
                    $keranjang = Keranjang::findOrFail($k->id);
                    $keranjang->update([
                        'jumlah' => $k->jumlah + 1,
                    ]);
                }
            }

            $isi = 'ada';
        } else {
            $isi = 'habis';
        }

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

    public function tampil_keranjang()
    {
        $transaksi = Transaksi::where('user_id', Auth::user()->id)->where('sts_transaksi', 'Y')->first();
        if (!empty($transaksi)) {
            return view('kasir.transaksi.keranjang', compact('transaksi'))->with('no', 1);
        }
    }

    public function tampil_nota()
    {
        $cek_tunggu = Transaksi::where('user_id', Auth::user()->id)->where('sts_transaksi', 'T')->count();

        $t = Transaksi::where('user_id', Auth::user()->id)->where('sts_transaksi', 'Y')->first();

        if (!empty($t->id)) {
            $k = Keranjang::where('transaksi_id', $t->id)->selectRaw('SUM( (harga * jumlah) - ((harga * jumlah) * diskon /100 ) ) as jml')->groupBy('transaksi_id')->first();
            $subdiskon = $k->jml - (($k->jml * $t->diskon) / 100);


            $pon = number_format(($k->jml - (($k->jml * diskon()) / 100)) / modull('POIN')->judul, 2, ',', '');
            $ambil = substr(trim($pon), 0, -3);

            if (modull('POIN')->isi != 0) {
                $pn = ($ambil < 1) ? 0 : $ambil * modull('POIN')->isi;
            } else {
                $pn = 0;
            }

            $data = [
                'petugas' => $t->user->nm_user,
                'tgl' => tgl_time($t->created_at),
                'kode' => $t->kd_transaksi,

                'ttlasl' => $k->jml - (($k->jml * diskon()) / 100),
                'sub' =>  'Rp. ' . number_format($k->jml - (($k->jml * diskon()) / 100), 0, ',', '.'),
                'ttl' =>  'Rp. ' . number_format($k->jml, 0, ',', '.'),
                'jumlah' => $k->jml,
                'tgu' => (empty($cek_tunggu)) ? '' : ' [ ' . $cek_tunggu . ' ]',

                'nm_member' => $t->member->nm_member,
                'kode_member' => $t->member->kd_member,

                'ongkir' => number_format($t->ongkir, 0, ',', '.'),
                'ongkirasl' => $t->ongkir,
                'bayar' => number_format($t->total, 0, ',', '.'),
                'sub2' => 'Rp. ' . number_format($t->ongkir + $subdiskon, 0, ',', '.'),
                'dbyasl' => $t->total,
                'sisa' => 'Rp. ' . number_format($t->total - ($t->ongkir + $subdiskon), 0, ',', '.'),
                'viabayar' => $t->via_bayar,

                'sts_antar' => $t->sts_antar,
                'dis' => $t->diskon . '%',

                'poin' => $pn


            ];
        } else {
            $data = [
                'petugas' => "-",
                'tgl' => "-",
                'kode' => 0,

                'ttlasl' => "",
                'sub' => "",
                'ttl' =>  'Rp. 0',
                'jumlah' => 0,
                'tgu' => (empty($cek_tunggu)) ? '' : ' [ ' . $cek_tunggu . ' ]',

                'nm_member' => "Pelanggan",
                'kode_member' => 0,
                'ongkir' => 0,
                'ongkirasl' => 0,
                'bayar' => "",
                'dbyasl' => 0,
                'viabayar' => "K",
                'sts_antar' => "N",
            ];
        }
        return response()->json($data);
    }

    public function destroy_keranjang(Request $request)
    {
        $k = Keranjang::where('id', $request->id)->first();
        $cek = Keranjang::where('transaksi_id', $k->transaksi_id)->count();
        if ($cek == 1) {
            Keranjang::findOrFail($request->id)->delete();
            Transaksi::findOrFail($k->transaksi_id)->delete();
        } else {
            Keranjang::findOrFail($request->id)->delete();
        }

        return response()->json();
    }

    public function edit_qty(Request $request)
    {
        $keranjang = Keranjang::findOrFail($request->id);
        $cek_stok = stok($keranjang->produk_id) - terjual($keranjang->produk_id) + $keranjang->jumlah;
        if ($request->value == null) {
        } else {
            if ($request->value <= $cek_stok) {
                $keranjang->update([
                    'jumlah' => $request->value,
                ]);
                $isi = 'ada';
            } else {
                $isi = 'habis';
            }
        }

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

    public function proses_tunggu(Request $request)
    {
        $t = Transaksi::where('kd_transaksi', $request->kode)->first();
        if (!empty($t)) {
            $transaksi = Transaksi::where('user_id', Auth::user()->id)->where('sts_transaksi', 'Y')->first();
            if (!empty($transaksi->id)) {
                $tran = Transaksi::findOrFail($transaksi->id);
                $tran->update([
                    'sts_transaksi' => "T",
                ]);

                $tran2 = Transaksi::findOrFail($t->id);
                $tran2->update([
                    'sts_transaksi' => $request->sts,
                ]);
            } else {
                $tran = Transaksi::findOrFail($t->id);
                $tran->update([
                    'sts_transaksi' => $request->sts,
                ]);
            }
        }

        return response()->json();
    }

    public function open_keranjang()
    {
        $isi = 'T';
        $transaksi = Transaksi::where('user_id', Auth::user()->id)->where('sts_transaksi', 'T')->get();
        if (!empty($transaksi)) {
            return view('kasir.transaksi.open', compact('transaksi', 'isi'))->with('no', 1);
        }
    }

    public function kode_member(Request $request)
    {
        $t = Transaksi::where('user_id', Auth::user()->id)->where('sts_transaksi', 'Y')->first();
        $k = Keranjang::where('transaksi_id', $t->id)->selectRaw('SUM(berat * jumlah)  as jml_berat')->groupBy('transaksi_id')->first();


        $m = Member::where('kd_member', $request->kode)->first();
        if (!empty($m->id)) {
            $kg = $k->jml_berat / 1000;
            if ($kg <= $m->ongkirmember->ongkir->berat) {
                $ongkir = $m->ongkirmember->ongkir->harga;
            } else {
                $ongkir = $m->ongkirmember->ongkir->harga * $kg / $m->ongkirmember->ongkir->berat;
            }
            $data = [
                'hasil' => 'ada',
                'kd' => $m->kd_member,
                'nm' => $m->nm_member,
                'alamat' => $m->ongkirmember->alamat,
                'ongkir' =>  $ongkir,
                'brt' => number_format($kg, 1, ',', '.') . ' Kg',
            ];
        } else {
            $data = [
                'hasil' => 'kosong',
                'kd' => 0,
                'nm' => '',
                'alamat' => '',
                'ongkir' => 0,
                'brt' => 0
            ];
        }

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

    public function cari_member(Request $request)
    {
        $member = Member::where('nm_member', 'like', '%' . $request->nama . '%')->get();
        $cnt = Member::where('nm_member', 'like', '%' . $request->nama . '%')->count();
        if (!empty($cnt)) {
            foreach ($member as $p) {
                $a = Ongkirmember::where('member_id', $p->id)->latest('id', 'ASC')->limit(1)->first();
                echo '<a href="#" class="list-group-item pilih" data-kd="' . $p->kd_member . '"> ' . $p->nm_member . ' || ' . $a->alamat . '</a>';
            }
        } else {
            echo 'kosong';
        }
    }

    public function simpan_transaksi(Request $request)
    {
        $transaksi = Transaksi::where('kd_transaksi', $request->kode)->first();
        if ($request->kode_member == 0) {
            $m = Member::where('kd_member', '0')->first();
            $member = $m->id;
        } else {
            $m = Member::where('kd_member', $request->kode_member)->first();
            $member = $m->id;
            if ($request->poin != 0) {
                $cek_poin = Poinbelanja::where('kodetran', $request->kode)->where('member_id', $member)->first();
                if (empty($cek_poin)) {
                    Poinbelanja::create([
                        'user_id' => Auth::user()->id,
                        'member_id' => $member,
                        'kodetran' => $request->kode,
                        'jml_poin' => $request->poin,
                        'sts_poin' => 'M',
                    ]);
                } else {
                    $cek_poin->update([
                        'jml_poin' => $request->poin,
                    ]);
                }
            }
        }

        $transaksi->update([
            'member_id' =>  $member,
            'jumlah' => $request->jumlahtotal,
            'ongkir' => $request->ongkir,
            'diskon' => $request->diskon,
            'total' => $request->ttl,
            'dibayar' => $request->dby,
            'sts_transaksi' => 'N',
            'sts_antar' => $request->sts_antar,
            'via_bayar' => $request->viabayar,
        ]);
        return response()->json();
    }

    public function cari_transaksi(Request $request)
    {
        $isi = $request->caridata;
        $cari = $request->cari;
        if ($isi == 'N' || $isi == 'T') {
            $transaksi = Transaksi::where('user_id', Auth::user()->id)->where('sts_transaksi', $request->caridata)->latest('id', 'DESC')
                ->where('kd_transaksi', 'like', '%' .  $cari . '%')
                ->orwhereHas('member', function ($query) use ($cari) {
                    $query->where('nm_member', 'like', '%' .  $cari . '%');
                })->limit(10)
                ->get();
            return view('kasir.transaksi.open', compact('transaksi', 'isi'))->with('no', 1);
        } else {
            $isi = 'P';
            $transaksi = Produk::where('kd_produk', 'like', '%' .  $cari . '%')
                ->orwhere('nm_produk', 'like', '%' .  $cari . '%')->limit(10)
                ->get();
            return view('kasir.transaksi.open', compact('transaksi', 'isi'))->with('no', 1);
        }
    }

    public function cek_harga()
    {
        $isi = 'P';
        $transaksi = Produk::limit(10)->get();
        return view('kasir.transaksi.open', compact('transaksi', 'isi'))->with('no', 1);
    }

    public function refund()
    {
        $isi = 'N';
        $transaksi = Transaksi::where('sts_transaksi', 'N')->where('jns_transaksi', 'OFF')->where('user_id', Auth::user()->id)->latest('id', 'DESC')->limit(10)->get();
        return view('kasir.transaksi.open', compact('transaksi', 'isi'))->with('no', 1);
    }

    public function cetak_struk(Request $request)
    {

        $t = Transaksi::where('kd_transaksi', $request->kode)->first();
        return view('kasir.transaksi.struk', compact('t'))->with('no', 1);
    }

    public function cetak_struk2(Request $request)
    {
        $t = Transaksi::where('kd_transaksi', $request->kode)->first();
        $keranjang = Keranjang::where('transaksi_id', $t->id)->get();
        $tgl = date('d-m-Y H:i', strtotime($t->created_at));

        $isipoin = poinmasuk($t->kd_transaksi);

        $connector = new WindowsPrintConnector(modull('PRINT')->isi);
        $printer = new Printer($connector);

        $printer->initialize();
        $printer->setJustification(Printer::JUSTIFY_CENTER);
        $printer->text(modull('PNT')->judul . "\n");
        $printer->text(modull('PNT')->gambar . " - " . modull('PNT')->link . "\n");
        $printer->text(modull('PNT')->isi . "\n");
        $printer->text("================================\n");

        $printer->initialize();
        $printer->setJustification(Printer::JUSTIFY_LEFT);
        $printer->text(printer_cek("NO.TRS   :", $t->kd_transaksi) . "\n");
        $printer->text(printer_cek("TANGGAL  :", $tgl) . "\n");
        $printer->text(printer_cek("MEMBER   :", $t->member->nm_member) . "\n");
        $printer->text(printer_cek("PETUGAS  :", $t->user->nm_user) . "\n");
        $printer->text("================================\n");

        $printer->initialize();
        $printer->setJustification(Printer::JUSTIFY_LEFT);
        foreach ($keranjang as $k) {
            $printer->text($k->produk->nm_produk . "\n");
            $printer->text(printer_cek($k->jumlah . " x " . number_format($k->harga - ($k->harga * $k->diskon) / 100, 0, ',', '.'), number_format(($k->harga - ($k->harga * $k->diskon) / 100) * $k->jumlah, 0, ',', '.'))  . "\n");
        }
        $printer->text("================================\n");

        $printer->initialize();
        $printer->setJustification(Printer::JUSTIFY_LEFT);
        if ($t->diskon != 0) {
            $printer->text(printer_cek("Subtotal       : Rp. ", number_format($t->jumlah, 0, ',', '.')) . "\n");
            $printer->text(printer_cek("Diskon         : % ", number_format($t->diskon, 0, ',', '.')) . "\n");
        }
        if ($t->sts_antar == 'Y') {
            $printer->text(printer_cek("Ongkir         : Rp. ", number_format($t->ongkir, 0, ',', '.')) . "\n");
        }
        $printer->text(printer_cek("Total          : Rp. ", number_format($t->total, 0, ',', '.')) . "\n");
        $printer->text(printer_cek("Bayar          : Rp. ", number_format($t->dibayar, 0, ',', '.')) . "\n");
        $printer->text(printer_cek("Kembali        : Rp. ", number_format($t->dibayar - $t->total, 0, ',', '.')) . "\n");
        $printer->text("================================\n");

        $printer->initialize();
        $printer->setJustification(Printer::JUSTIFY_CENTER);
        $printer->text(modull('PTX')->judul . "\n");
        if ($isipoin != 0) {
            $printer->text("Poin " . $isipoin . "\n");
        }
        $printer->text(modull('PTX')->isi . "\n");
        $printer->feed(1);
        $printer->text(modull('PTX')->link . "\n");

        $printer->feed(3);
        $printer->close();
        return response()->json();
    }

    public function print_label(Request $request)
    {

        $t = Transaksi::where('kd_transaksi', $request->kode)->first();
        $cek = Ongkirmember::where('member_id', $t->member_id)->count();
        if (modull('PRINT')->status == 'N') {
            if (empty($cek)) {
                $a = 0;
            } else {
                $a = Ongkirmember::where('member_id', $t->member_id)->first();
            }
            return view('kasir.transaksi.lable', compact('t', 'a'));
        } else {
            $tgl = date('d-m-Y H:i', strtotime($t->created_at));
            $a = Ongkirmember::where('member_id', $t->member_id)->first();

            $connector = new WindowsPrintConnector(modull('PRINT')->isi);
            $printer = new Printer($connector);

            $printer->initialize();
            $printer->setJustification(Printer::JUSTIFY_CENTER);
            $printer->text(modull('PNT')->judul . "\n");
            $printer->text("================================\n");
            $printer->setTextSize(5, 5 . "\n");
            $printer->text($t->kd_transaksi . "\n");
            $printer->selectPrintMode(Printer::MODE_EMPHASIZED);
            $printer->text("================================\n");
            $printer->feed(1);
            $printer->text($t->member->nm_member . "\n");
            $printer->text($t->member->hp_member . "\n");
            $printer->text($tgl . "\n");
            $printer->text("================================\n");
            $printer->text("Alamat Pengiriman \n");
            $printer->text($a->alamat . "\n");
            $printer->selectPrintMode();
            $printer->feed(3);
            $printer->close();

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

    public function update_kurir(Request $request)
    {
        Kurir::create([
            'transaksi_id' => $request->id,
            'karyawan_id' => $request->karyawan,
        ]);
        return response()->json();
    }


    public function penjualan()
    {
        $penjualan  = Transaksi::pencarian()->where('sts_transaksi', 'N')->latest()->paginate(10);
        $data = [
            'title' => 'Ramizah Store | Data Penjualan',
            'page' => 'Data Penjualan',
            'menuActive' => 'penjualan',
            'menuOpen' => 'penjualan',
        ];
        return view('admin.data.penjualan', compact('data', 'penjualan'))->with('no', 1);
    }

    public function detail_penjualan(Request $request)
    {
        $t = Transaksi::where('id', $request->id)->first();
        return view('admin.data.detail_penjualan', compact('t'))->with('no', 1);
    }

    public function destroy_all_penjualan(Request $request)
    {
        $ids = $request->allVals;
        foreach ($ids as  $id) {
            $c =  Transaksi::where('id', $id)->first();
            $baryar = Pembayaran::where('transaksi_id', $c->id)->first();
            $poin = Poinbelanja::where('kodetran', $c->kd_transaksi)->first();
            if (!empty($poin)) {
                $poin->delete();
            }
            if (!empty($baryar)) {
                Storage::delete('public/struk/' .  $baryar->struk);
                $baryar->delete();
            }
            $c->delete();
        }
        return response()->json();
    }
}
