<?php

namespace App\Http\Controllers;

use App\Models\Produk;
use App\Models\Stok;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class StokController extends Controller
{
    public function index()
    {
        $stok = Stok::pencarian()->latest()->paginate(10);
        $data = [
            'title' => 'Ramizah Store | Stok',
            'page' => 'Stok',
            'menuActive' => 'stok',
            'menuOpen' => 'stok',
        ];
        return view('kasir.stok.stok', compact('data', 'stok'))->with('no', 1);
    }

    public function kode_produk(Request $request)
    {
        $kode = $request->kode;
        $p = Produk::where('kd_produk', $kode)->first();
        if (!empty($p->id)) {
            $data = [
                'hasil' => 'ada',
                'kd' => $p->kd_produk,
                'nm' => $p->nm_produk,
                'idp' => $p->id,
            ];
        } else {
            $data = [
                'hasil' => 'kosong',
                'kd' => "",
                'nm' => "",
                'idp' => "",
            ];
        }
        return response()->json($data);
    }

    public function cari_produk(Request $request)
    {
        $produk = Produk::where('nm_produk', 'like', '%' . $request->nama . '%')->get();
        $cnt = Produk::where('nm_produk', 'like', '%' . $request->nama . '%')->count();
        if ($request->nama != "") {
            if (!empty($cnt)) {
                foreach ($produk as $p) {
                    echo '<a href="#" class="list-group-item pilih" data-kd="' . $p->kd_produk . '"> ' . $p->kd_produk . ' || ' . $p->nm_produk . '</a>';
                }
            } else {
                echo 'kosong';
            }
        } else {
            echo 'kosong';
        }

        // return view('kasir.stok.dtproduk', compact('produk'));
    }

    public function simpan_stok(Request $request)
    {
        Stok::create([
            'user_id' => Auth::user()->id,
            'produk_id' => $request->id,
            'jml_masuk' => $request->jml,
        ]);
        return response()->json();
    }

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

    public function destroy_all_stok(Request $request)
    {
        $ids = $request->allVals;
        foreach ($ids as  $id) {
            Stok::findOrFail($id)->delete();
        }

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