<?php

namespace App\Http\Controllers;

use App\Models\Admin;
use App\Models\Brand;
use App\Models\Kasir;
use App\Models\Mesin;
use App\Models\Paket;
use App\Models\Barang;
use App\Models\Laundry;
use App\Models\Pegawai;
use App\Models\Transaksi;
use App\Models\KepalaToko;
use App\Models\PegawaiPaket;
use Illuminate\Http\Request;
use App\Models\BahanBakuPaket;
use App\Models\DetailTransaksiMesin;
use App\Models\Transaksi_Detail;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;
use App\Models\RiwayatPengeluaranBarang;
use Illuminate\Support\Facades\Validator;
use SebastianBergmann\GlobalState\Exception;

class transaksiController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (Auth::user()->role == 'superadmin') {
            $data = Transaksi::all();
        } elseif (Auth::user()->role == 'admin') {
            $admin = Admin::where('users_id', Auth::user()->id)->first();
            $admin_brand = $admin->brand_id;
            $data = Transaksi::join('laundry', 'laundry.id', '=', 'transaksi.laundry_id')
                ->where('laundry.brand_id', $admin_brand)
                ->where('transaksi.status_transaksi', 'baru')
                ->select('transaksi.*')->get();
        } else {
            if (Auth::user()->role == 'pegawai') {
                $pegawai = Pegawai::where('users_id', Auth::user()->id)->first();
                $laundry_id = $pegawai->laundry_id;
                $data = Transaksi::where('laundry_id', $laundry_id)->where('status_transaksi', 'baru')->orderby('id', 'desc')->get();
            } else {
                $kepala_toko = KepalaToko::where('users_id', Auth::user()->id)->first();
                $laundry_id = $kepala_toko->laundry_id;
                $data = Transaksi::where('laundry_id', $laundry_id)->where('status_transaksi', 'baru')->orderby('id', 'desc')->get();
            }
        }

        return view('transaksi.index', compact('data'));
    }

    public function index_proses()
    {
        if (Auth::user()->role == 'superadmin') {
            $data = Transaksi::all();
        } elseif (Auth::user()->role == 'admin') {
            $admin = Admin::where('users_id', Auth::user()->id)->first();
            $admin_brand = $admin->brand_id;
            $data = Transaksi::join('laundry', 'laundry.id', '=', 'transaksi.laundry_id')
                ->where('laundry.brand_id', $admin_brand)
                ->where('transaksi.status_transaksi', 'proses')
                ->select('transaksi.*')->get();
        } else {
            if (Auth::user()->role == 'pegawai') {
                $pegawai = Pegawai::where('users_id', Auth::user()->id)->first();
                $laundry_id = $pegawai->laundry_id;
                $data = Transaksi::where('laundry_id', $laundry_id)->where('status_transaksi', 'proses')->orderby('id', 'desc')->get();
            } else {
                $kepala_toko = KepalaToko::where('users_id', Auth::user()->id)->first();
                $laundry_id = $kepala_toko->laundry_id;
                $data = Transaksi::where('laundry_id', $laundry_id)->where('status_transaksi', 'proses')->orderby('id', 'desc')->get();
            }
        }

        return view('transaksi.index', compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        $validate = Validator::make($request->all(), [
            'pelanggan_id' => 'required',
            'laundry_id' => 'required',
            'kasir_id' => 'required',
            'produk' => 'required'
        ]);

        if ($validate->fails()) {
            return redirect()
                ->back()
                ->with('error', $validate->errors()->first());
        }

        // Buat kode transaksi unik
        $kodeTransaksi = 'TRX-' . time();
        // mengecek dulu di transaksi laundry ini sudah ada transaksi atau belum dan ambil paling terakhir
        $transaksi = Transaksi::where('laundry_id', $request->laundry_id)->orderBy('id', 'desc')->first();
        if ($transaksi != null) {
            $laundry = Laundry::find($request->laundry_id);
            $transaksi = Transaksi::where('laundry_id', $request->laundry_id)->orderBy('id', 'desc')->first();
            $kode = $transaksi->kode_transaksi;
            $number = (int) substr($kode, strrpos($kode, '-') + 1);
            // Menambahkan 1 pada angka tersebut
            $newNumber = $number + 1;
            $kodeTransaksi = 'TRX-' . $laundry->brand->id . '-' . $laundry->id . '-' . $newNumber;
        } else {
            $laundry = Laundry::find($request->laundry_id);
            $kodeTransaksi = 'TRX-' . $laundry->brand->id . '-' . $laundry->id . '-' . 1;;
        }

        $auth = Auth::user()->id;
        $pegawai = Pegawai::where('users_id', $auth)->first();

        // cari kasir
        $kasir = Kasir::where('id', $request->kasir_id)->first();
        $cek_trx = Transaksi::where('laundry_id', $request->laundry_id)
            ->where('kasir_id', $request->kasir_id)
            ->count();
        if ($cek_trx > 0) {
            // $last_trx = Transaksi::where('laundry_id', $request->laundry_id)
            //     ->where('kasir_id', $request->kasir_id)
            //     ->orderBy('id', 'desc')
            //     ->first();
            $balanced_trx = $request->total_harga;
        } else {
            $balanced_trx = $kasir->opening_balance + $request->total_harga;
        }

        // Simpan transaksi ke tabel 'transaksi'
        $transaksi = Transaksi::create([
            'kode_transaksi' => $kodeTransaksi,
            'pelanggan_id' => $request->pelanggan_id,
            'pegawai_id' => $pegawai->id,
            'laundry_id' => $request->laundry_id,
            'kasir_id' => $request->kasir_id,
            'total_harga' => $request->total_harga,
            'tgl_transaksi' => date('Y-m-d H:i:s'),
            'tgl_selesai' => $request->tgl_selesai,
            'is_bayar' => $request->is_bayar ? 1 : 0,
            'is_cash' => $request->is_cash ? 1 : 0,
            'metode_id' => $request->metode_id,
            'parfum_id' => $request->parfum_id,
            'balanced_trx' =>  $balanced_trx,
            'keterangan' => $request->keterangan,
        ]);

        // Simpan detail transaksi ke tabel 'transaksi_detail'
        foreach ($request->produk as $id => $produk) {
            Transaksi_Detail::create([
                'transaksi_id' => $transaksi->id,
                'paket_id' => $id,
                'qty' => $produk['qty'],
                'harga' => $produk['harga'],
                'total_harga' => $produk['harga'] * $produk['qty'],
                'parfum_id' => $request->parfum_id,
                'status' => 'baru',  // Default status, bisa diubah sesuai kebutuhan
            ]);
        }

        // Redirect atau kembalikan response sesuai kebutuhan
        return redirect()->route('kasir.index')->with('success', 'Transaksi berhasil dibuat.');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $transaksi = Transaksi::where('id', $id)->first();
        $detail = Transaksi_Detail::where('transaksi_id', $id)->get();
        $pegawai = [];
        foreach ($detail as $key => $value) {
            $pegawai = PegawaiPaket::where('paket_id', $value->paket_id)->get();
        }
        return view('transaksi.detail', compact('transaksi', 'detail'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {

        $paket_idnya = $request->paket_idnya;
        try {
            DB::beginTransaction();

            $transaksi_detail = Transaksi_Detail::find($id);
            $transaksi_detail->update([
                'status' => 'proses',
                'pegawai_id' => $request->pegawai_id,
                // 'mesin_id' => $request->mesin_id,
            ]);

            // cek  transaksi apakah sudah diproses semua ?
            // Cari transaksi_detail dengan id_transaksi = 2 yang tidak berstatus 'proses'
            $transaksiDetailNotProses = Transaksi_Detail::where('transaksi_id', $transaksi_detail->transaksi_id)
                ->where('status', '!=', 'proses')
                ->exists();

            if (!$transaksiDetailNotProses) {
                // Jika semua transaksi_detail sudah berstatus 'proses', update tabel transaksi
                Transaksi::where('id', 2)->update(['status_transaksi' => 'proses']);
            }

            // create tabel detail trx mesin untuk menyimpan data mesin yang dipilih pada detail trx
            foreach ($request->mesin_id as $key => $value) {
                $detail_trx_mesin = DetailTransaksiMesin::create([
                    'detail_trx_id' => $id,
                    'mesin_id' => $value
                ]);
            }

            $bahan_baku = BahanBakuPaket::where('paket_id', $paket_idnya)->get();
            foreach ($bahan_baku as $value) {
                $min_bahan = $value->qty;
                $total_bahan = $transaksi_detail->qty * $min_bahan;

                $barang = Barang::where('id', $value->barang_id)->first();
                if ($barang) {
                    $volume_awal = $barang->volume_total;

                    $barang->update([
                        'volume_total' => $volume_awal - $total_bahan
                    ]);

                    RiwayatPengeluaranBarang::create([
                        'detail_trx_id' => $transaksi_detail->id,
                        'paket_id' => $paket_idnya,
                        'barang_id' => $barang->id,
                        'qty' => $total_bahan,
                        'volume_awal' => $volume_awal,
                        'volume_akhir' => $barang->volume_total,
                        'satuan' => $barang->satuan,
                        'tgl_pengeluaran' => now(),
                    ]);
                }
            }

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            Log::error($e->getMessage());
        }

        return redirect()->back()->with('success', 'Data Transaksi Berhasil Diupdate');
    }



    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    public function transaksinya($kode_transaksi)
    {

        $transaksi = Transaksi::where('kode_transaksi', $kode_transaksi)
            ->with('pelanggan')
            ->first();

        if (!$transaksi) {
            return response()->json(
                ['error' => 'Transaksi tidak ditemukan gess'],
                '404'
            );
        }

        // Cek apakah transaksi belum dibayar
        if ($transaksi->is_bayar == 1 && $transaksi->is_cash == '1') {
            // Jika belum dibayar, kembalikan data transaksi
            return response()->json($transaksi);
        }

        // Jika sudah dibayar, cek apakah transaksi cash
        if ($transaksi->is_bayar == 0) {
            return response()->json($transaksi);
        } else {
            return response()->json(['error' => 'Transaksi ini tidak dapat di setor gess'], '404');
        }
    }
}
