<?php

namespace App\Http\Controllers;

use App\Http\Requests\BarangRequest;
use App\Models\Barangs;
use App\Models\Kategoris;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class BarangController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (cekAkses(Auth::user()->id, "Barang", "lihat") != TRUE) {
            abort(403, 'unauthorized');
        }

        $title = 'Barang';
        return view('barang.barang', compact('title'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        if (cekAkses(Auth::user()->id, "Barang", "tambah") != TRUE) {
            abort(403, 'unauthorized');
        }

        $modal_title = "Tambah Data";
        $tombol = "Tambah";
        $barang = new Barangs();
        $kategori = Kategoris::where('trashed', 0)->pluck('nama', 'id');

        return view('barang.barang-action', compact('modal_title', 'tombol', 'kategori', 'barang'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(BarangRequest $request, Barangs $barang)
    {
        if (cekAkses(Auth::user()->id, "Barang", "tambah") != TRUE) {
            abort(403, 'unauthorized');
        }

        $harga     = $request->harga;
        $harga_set = str_replace(',', '', $harga);

        $barang->nama        = $request->nama;
        $barang->harga       = $harga_set;
        $barang->categori_id = $request->categori_id;
        $barang->created_by  = Auth::user()->name;
        $barang->updated_by  = Auth::user()->name;
        $barang->save();

        return response()->json([
            'status'  => 'success',
            'message' => 'Data berhasil di tambah'
        ]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Barangs $barang)
    {
        if (cekAkses(Auth::user()->id, "Barang", "ubah") != TRUE) {
            abort(403, 'unauthorized');
        }

        $modal_title = "Ubah Data";
        $tombol      = "ubah";
        $kategori    = Kategoris::where('trashed', 0)->pluck('nama', 'id');

        return view('barang.barang-action', compact('modal_title', 'tombol', 'barang', 'kategori'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Barangs $barang)
    {
        if (cekAkses(Auth::user()->id, "Barang", "ubah") != TRUE) {
            abort(403, 'unauthorized');
        }

        $harga = $request->harga;
        $harga_set = str_replace(',', '', $harga);

        $barang->nama        = $request->nama;
        $barang->harga       = $harga_set;
        $barang->categori_id = $request->categori_id;
        $barang->updated_by  = Auth::user()->name;
        $barang->save();

        return response()->json([
            'status'  => 'success',
            'message' => 'Data berhasil di ubah'
        ]);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Barangs $barang)
    {
        if (cekAkses(Auth::user()->id, "Barang", "hapus") != TRUE) {
            abort(403, 'unauthorized');
        }

        $barang->trashed = 1;
        $barang->updated_by = Auth::user()->name;
        $barang->save();

        return response()->json([
            'status'  => 'success',
            'message' => 'Data berhasil di hapus'
        ]);
    }

    function data_list(Request $req)
    {
        $list      = $this->get_list($req);
        $data      = array();
        $no        = $req['start'];
        foreach ($list as $field) {
            $btn_edit = '';
            $btn_delete = '';
            if (cekAkses(Auth::user()->id, "Supplier", "ubah") == TRUE) {
                $btn_edit   = '<button type="button" data-id=' . $field->id_barang . ' data-jenis="edit" class="btn btn-warning btn-sm action"><i class="ti-pencil"></i></button>';
            }
            if (cekAkses(Auth::user()->id, "Supplier", "hapus") == TRUE) {
                $btn_delete = '<button type="button" data-id=' . $field->id_barang . ' data-jenis="delete" class="btn btn-danger btn-sm action"><i class="ti-trash"></i></button>';
            }

            $btn        = $btn_edit . ' ' . $btn_delete;

            $no++;
            $row   = array();
            $row[] = $no;
            $row[] = $field->nama_barang;
            $row[] = $field->nama_kategori;
            $row[] = number_format($field->harga);
            $row[] = $field->created_at;
            $row[] = $field->created_by;
            $row[] = $btn;
            $data[] = $row;
        }

        $output = array(
            "draw"            => $req['draw'],
            "recordsTotal"    => 0,
            "recordsFiltered" => $this->count_filtered($req, 'filter'),
            "data"            => $data,
        );
        return response()->json($output);
    }

    function get_list(Request $req)
    {
        $query = $this->sql_list($req);

        if ($req['length'] != -1)
            $query->offset($req['start'])
                ->limit($req['length']);
        $query->orderBy("A1.id_barang", "DESC");
        return $query->get();
    }


    function sql_list(Request $request)
    {
        $seacrh    = $request->search;
        $where  = (strlen($seacrh) > 0) ? " AND A.nama LIKE '%$seacrh%' OR A.created_by LIKE '%$seacrh%' OR B.nama LIKE '%$seacrh%'" : "";
        $sql = "(SELECT A.id AS id_barang, B.id AS id_kategoris, A.nama AS nama_barang, B.nama AS nama_kategori, A.created_by, A.harga, A.created_at
                    FROM  barangs AS A 
                    INNER JOIN kategoris AS B ON B.id=A.categori_id
                    WHERE A.trashed=0
                    $where 
                ) AS A1";

        $sqls = DB::table(DB::raw($sql));
        return $sqls;
    }

    function count_filtered($req, $filter = '')
    {
        $query = $this->sql_list($req, $filter);
        $query = $query->get();
        return $query->count();
    }
}
