<?php

namespace App\Http\Controllers;

use App\Models\Karyawan;
use App\Models\Keranjang;
use App\Models\Member;
use App\Models\Modul;
use App\Models\Ongkirmember;
use App\Models\Pembayaran;
use App\Models\Poinbelanja;
use App\Models\Produk;
use App\Models\Transaksi;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Surfsidemedia\Shoppingcart\Facades\Cart;

class OrderController extends Controller
{

    public function add_cart(Request $request)
    {
        $p = Produk::where('kd_produk', $request->kode)->first();
        $hargadis = $p->harga_jual - ($p->harga_jual * $p->diskon / 100);
        Cart::add([
            [
                'id' => $p->id,
                'name' => $p->nm_produk,
                'qty' => 1,
                'price' =>  $hargadis
            ]
        ]);
        return response()->json();
    }

    public function add_cart_detail(Request $request)
    {
        $p = Produk::where('kd_produk', $request->kode)->first();
        $hargadis = $p->harga_jual - ($p->harga_jual * $p->diskon / 100);
        Cart::add([
            [
                'id' => $p->id,
                'name' => $p->nm_produk,
                'qty' => $request->qty,
                'price' =>  $hargadis
            ]
        ]);
        return response()->json();
    }

    public function qty_update(Request $request)
    {
        $stok = stok($request->idp) - terjual($request->idp);
        $rowId = $request->id;
        $p = Cart::get($rowId);

        if ($request->nm == 'plus') {
            if ($stok != $p->qty) {
                $qty = $p->qty + 1;
                Cart::update($rowId, $qty);
            } else {
                Cart::update($rowId, $p->qty);
            }
        } else {
            $qty = $p->qty - 1;
            if ($qty != 0) {
                Cart::update($rowId, $qty);
            }
        }

        return response()->json();
    }

    public function hapus_cart(Request $request)
    {
        Cart::remove($request->id);
        return response()->json();
    }

    public function view_cart()
    {
        return  Cart::count();
    }

    public function checkout()
    {

        $bank = Modul::where('kode', 'BANK')->latest()->get();
        $m = Member::where('id', Auth::user()->id)->first();

        if (ongkir($m->id)->sts_alamat == "N") {
            return back()->with(['error' => 'Akun anda belum di Verifikasi  pihak toko, silahkan tunggu atau hubungi kontak toko!']);
        }


        $total = [];
        $berat = [];
        foreach (Cart::content() as $row) {
            $p = Produk::where('id', $row->id)->first();
            $berat[] = $p->berat;
            $total[] = $row->price * $row->qty;
        }
        // berat
        $ttlberat = array_sum($berat);
        // subtotal
        $subtotal = array_sum($total);
        // harga diskon
        $hargadisk = $subtotal - ($subtotal * diskon()) / 100;

        // jml poin 
        $pon = number_format($hargadisk / modull('POIN')->judul, 2, ',', '');
        $ttlpoin = substr(trim($pon), 0, -3);

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

        // status ongkir
        $a = Ongkirmember::where('member_id', $m->id)->first();
        $kg =  $ttlberat / 1000;
        if ($kg <= $a->ongkir->berat) {
            $harga_ongkir = $a->ongkir->harga;
        } else {
            $harga_ongkir = $a->ongkir->harga * $kg;
        }

        // status Alamat
        if (ongkir($m->id)->sts_alamat == "Y") {
            $ongkir =  $harga_ongkir;
        } else {
            $ongkir =  0;
        }

        //grand total
        $ttl =  $hargadisk +  $ongkir;

        $data = [
            'title' => 'Ramizah Store | Buat Pesanan',
            'page' => ' Buat Pesanan',
            'menuActive' => 'order',
            'menuOpen' => 'order',
            'ongkir' =>  $ongkir,
            'poin' =>  $pn,
            'ttl' =>  $ttl,
            'subtotal' =>  $subtotal,
            'ttlasli' =>  $hargadisk,
        ];
        return view('home.checkout', compact('data', 'm', 'bank'));
    }

    public function order(Request $request)
    {
        $m = Member::where('id', Auth::user()->id)->first();
        $u = User::latest('id', 'asc')->first();
        if ($request->stsongkir == "Y") {
            $jml = $request->ttl_ongkir;
            $ongkir = $request->ongkirhid;
        } else {
            $jml = $request->ttlasli;
            $ongkir = 0;
        }
        $kode = kodetransaksi();
        $id = Transaksi::create([
            'user_id' => $u->id,
            'member_id' => $m->id,
            'kd_transaksi' => $kode,
            'jumlah' =>   $request->subtotal,
            'ongkir' =>  $ongkir,
            'diskon' => diskon(),
            'total' => $jml,
            'dibayar' => 0,
            'sts_transaksi' => 'T',
            'via_bayar' => 'T',
            'jns_transaksi' => 'ON',
            'sts_antar' => $request->stsongkir,
            'ip_address' => getClientIP(),
        ])->id;

        foreach (Cart::content() as $row) {
            $p = Produk::where('id', $row->id)->first();
            Keranjang::create([
                'transaksi_id' => $id,
                'produk_id' => $p->id,
                'berat' => $p->berat,
                'harga' => $p->harga_jual,
                'jumlah' => $row->qty,
                'diskon' => $p->diskon,
            ]);
            Cart::remove($row->rowId);
        }

        if ($request->poinhid != 0) {
            $cek_poin = Poinbelanja::where('kodetran', $kode)->where('member_id', $m->id)->first();
            if (empty($cek_poin)) {
                Poinbelanja::create([
                    'user_id' => $u->id,
                    'member_id' => $m->id,
                    'kodetran' => $kode,
                    'jml_poin' => $request->poinhid,
                    'sts_poin' => 'M',
                ]);
            } else {
                $cek_poin->update([
                    'jml_poin' => $request->poin,
                ]);
            }
        }

        Pembayaran::create([
            'transaksi_id' => $id,
            'bank_id' => $request->via_tranfer,
            'sts_transfer' => 'N',
            'struk' => '',
            'expired' => date('Y-m-d H:i:s', time() + 60 * 10),
        ]);

        return redirect('invoice/' . $kode)->with(['success' => 'Data Pesanan Berhasil Dikirim, Silahkan melakukan pembayaran!']);
    }


    public function invoice($kode)
    {
        $t = Transaksi::where('kd_transaksi', $kode)->first();
        $keranjang = Keranjang::where('transaksi_id', $t->id)->get();
        $p = Pembayaran::where('transaksi_id', $t->id)->first();
        $d = Modul::where('id', $p->bank_id)->first();
        $data = [
            'title' => 'Ramizah Store | Buat Pesanan',
            'page' => ' Buat Pesanan',
            'menuActive' => 'order',
            'menuOpen' => 'order',
        ];
        return view('home.invoice', compact('data', 't', 'keranjang', 'p', 'd'));
    }

    public function bukti_transfer(Request $request)
    {
        $kode = $request->kode;
        if ($request->hasFile('struk')) {
            // //upload image
            $image = $request->file('struk');
            $image->storeAs('public/struk', $image->hashName());
            $isi = $image->hashName();
        } else {
            return redirect('invoice/' . $kode)->with(['error' => 'Struk gagal di kirim!']);
            $isi = '';
        }


        $id = $request->id;
        $bayar = Pembayaran::findOrFail($id);
        $bayar->update([
            'sts_transfer' => 'T',
            'struk' =>  $isi,
            'tgl_bayar' =>  date('Y-m-d H:i:s'),
        ]);
        return redirect('invoice/' . $kode)->with(['success' => 'Struk Pembayaran Berhasil Dikirim, Pesanan Anda akan segera kami proses, Terimakasih atas kepercayaan anda!']);
    }

    public function order_online()
    {
        $karyawan = Karyawan::latest()->get();
        $order  = Pembayaran::pencarian()->latest()->paginate(10);
        $data = [
            'title' => 'Ramizah Store | Order Online',
            'page' => 'Order Online',
            'menuActive' => 'order',
            'menuOpen' => 'order',
        ];
        return view('kasir.order.order', compact('data', 'order', 'karyawan'))->with('no', 1);
    }

    public function cek_tansfer(Request $request)
    {
        $p = Pembayaran::where('id', $request->id)->first();
        $d = Modul::where('id', $p->bank_id)->first();
        return view('kasir.order.v_transfer', compact('p', 'd'));
    }

    public function konfirmasi_pembayaran(Request $request)
    {
        $bayar = Pembayaran::where('id', $request->id)->first();
        $bayar->update([
            'sts_transfer' => 'Y',
            'expired' => date('Y-m-d H:i:s'),
        ]);
        $trans = Transaksi::where('id', $bayar->transaksi_id)->first();
        $trans->update([
            'user_id' => Auth::user()->id,
            'dibayar' =>   $trans->total,
            'sts_transaksi' => 'N',
        ]);
        return redirect('order-online')->with(['success' => 'Pembayaran berhasil dikonfirmasi!']);
    }

    public function update_diterima($id)
    {
        $bayar = Pembayaran::findOrFail($id);
        $bayar->update([
            'tgl_diterima' =>  date('Y-m-d H:i:s'),
        ]);
        return redirect('order-online')->with(['success' => 'Status Orderan berhasil diupdate!']);
    }

    public function destroy($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 redirect('order-online')->with(['success' => 'Status Orderan berhasil dihapus!']);
    }
}
