<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Admin;
use App\Models\Paket;
use App\Models\Laundry;
use App\Models\Pegawai;
use App\Models\KepalaToko;
use App\Models\PegawaiPaket;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class pegawaiController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if (Auth::user()->role == 'superadmin') {
            $laundry = Laundry::all();
            $data = User::where('role', 'pegawai')->get();
            $pegawai = [];
            foreach ($data as $d) {
                $peg = Pegawai::where('users_id', $d->id)->first();
                $pegawai[] = $peg;
            }
        } elseif (Auth::user()->role == 'admin') {
            $akun = Auth::user()->id;
            $admin = Admin::where('users_id', $akun)->first();
            $admin_brand = $admin->brand_id;
            $pegawai = Pegawai::join('laundry', 'laundry.id', '=', 'pegawai.laundry_id')
                ->where('laundry.brand_id', $admin_brand)
                ->get(['pegawai.*', 'pegawai.status as pegawai_status', 'laundry.status as laundry_status']);
            $laundry = Laundry::where('brand_id', $admin->brand_id)->get();
            $paket = Paket::join('laundry', 'laundry.id', '=', 'paket.laundry_id')
                ->where('laundry.brand_id', $admin_brand)
                ->get(['paket.*', 'laundry.status as laundry_status']);
        } else {
            if (Auth::user()->role == 'pegawai') {
                $pegawai_on = Pegawai::where('users_id', Auth::user()->id)->first();
                $pegawai = Pegawai::where('laundry_id', $pegawai_on->laundry_id)->get();
                $laundry = Laundry::where('id', $pegawai_on->laundry_id)->first();
                $paket = Paket::where('laundry_id', $pegawai_on->laundry_id)->get();
            } elseif (Auth::user()->role == 'kepala_toko') {
                $akun = Auth::user()->id;
                $kepala_toko = KepalaToko::where('users_id', $akun)->first();
                $pegawai = Pegawai::join('laundry', 'laundry.id', '=', 'pegawai.laundry_id')
                    ->where('laundry.id', $kepala_toko->laundry_id)
                    ->get(['pegawai.*', 'pegawai.status as pegawai_status', 'laundry.status as laundry_status']);
                $laundry = Laundry::where('id', $kepala_toko->laundry_id)->first();
                $paket = Paket::where('laundry_id', $kepala_toko->laundry_id)->get();
            }
        }
        return view('pegawai.index', compact('laundry', 'pegawai', 'paket'));
    }

    /**
     * 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)
    {

        $validasi = Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required',
            'email' => 'required',
            'nama' => 'required',
            'alamat' => 'required',
        ]);

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

        $user = User::create([
            'username' => $request->input('username'),
            'password' => bcrypt($request->input('password')),
            'email' => $request->input('email'),
            'role' => 'pegawai',
        ]);
        $user->save();

        $pegawai = new \App\Models\Pegawai();
        $pegawai->users_id = $user->id;
        $pegawai->laundry_id = $request->input('laundry_id');
        $pegawai->nama = $request->input('nama');
        $pegawai->alamat = $request->input('alamat');

        if ($request->hasFile('foto')) {
            $file = $request->file('foto');
            $extension = $file->getClientOriginalExtension();
            $filename = 'profile-' . time() . '.' . $extension;
            $file->storeAs('public/img', $filename);
            $pegawai->foto = $filename;
        } else {
            $pegawai->foto = 'default.png';
        }
        $pegawai->no_telp = $request->input('no_telp');
        $pegawai->gaji_pokok = $request->input('gaji_pokok');
        $pegawai->komisi_harian = $request->input('komisi_harian');
        $pegawai->save();


        foreach ($request->input('paket_id') as $key => $value) {
            $pegawai_paket = new PegawaiPaket();
            $pegawai_paket->paket_id = $value;
            $pegawai_paket->pegawai_id = $pegawai->id;
            $pegawai_paket->komisi_paket = $request->input('komisi_perpaket');
            $pegawai_paket->save();
        }

        return redirect('/pegawai')->with('success', 'Data Berhasil Ditambahkan');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = Pegawai::where('users_id', $id)->first();
        $pegawai_paket = PegawaiPaket::where('pegawai_id', $data->id)->get();

        return view('pegawai.detail', compact('data', 'pegawai_paket'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if (Auth::user()->role == 'superadmin') {
            $akun = User::find($id);
            $data = Pegawai::where('users_id', $id)->first();
            $laundry = Laundry::all();
            $paket = PegawaiPaket::all();
        } elseif (Auth::user()->role == 'admin') {
            $akun = User::find($id);
            $data = Pegawai::where('users_id', $id)->first();
            $admin = Admin::where('users_id', auth()->user()->id)->first();
            $admin_brand = $admin->brand_id;
            $laundry = Laundry::where('brand_id', $admin_brand)->get();
            $paket = PegawaiPaket::where('pegawai_id', $data->id)->get();
        } else {
            $akun = User::find($id);
            $data = Pegawai::where('users_id', $id)->first();
            $laundry = Laundry::where('id', $data->laundry_id)->first();
            $paket = PegawaiPaket::where('pegawai_id', $data->id)->get();
        }
        return view('pegawai.edit', compact('data', 'laundry', 'paket'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $pegawai = Pegawai::find($id);
        if (!$pegawai) {
            return redirect()->back()->with('error', 'Pegawai tidak ditemukan.');
        }

        // Update data Pegawai
        $pegawai->laundry_id = $request->input('laundry_id');
        $pegawai->nama = $request->input('nama');
        $pegawai->alamat = $request->input('alamat');
        $pegawai->no_telp = $request->input('no_telp');

        if ($request->hasFile('foto')) {
            $file = $request->file('foto');
            $extension = $file->getClientOriginalExtension();
            $filename = 'profile-' . time() . '.' . $extension;
            $file->storeAs('public/img', $filename);
            $pegawai->foto = $filename;
        }
        $pegawai->update();

        $akun = User::find($pegawai->users_id);
        if (!$akun) {
            return redirect()->back()->with('error', 'Akun pengguna tidak ditemukan.');
        }

        // Update data User
        $akun->username = $request->input('username');
        $akun->email = $request->input('email');


        if ($request->input('password')) {
            $akun->password = bcrypt($request->input('password'));
        }
        $akun->update();

        return redirect('/pegawai')->with('success', 'Data Berhasil Diubah');
    }

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

    public function aktifasi($id)
    {
        $pegawai = Pegawai::find($id);
        if ($pegawai->status == 'aktif') {
            $pegawai->status = 'tidak aktif';
        } else {
            $pegawai->status = 'aktif';
        }
        $pegawai->update();
        return redirect()->route('pegawai.index')->with('success', 'Status pegawai berhasil diubah');
    }

    public function tambahPaket($id, Request $request)
    {
        foreach ($request->input('paket_id') as $key => $value) {
            // Cek apakah PegawaiPaket sudah ada berdasarkan pegawai_id dan paket_id
            $pegawai_paket = PegawaiPaket::where('pegawai_id', $id)
                ->where('paket_id', $value)
                ->first();

            // Jika belum ada, buat instans baru
            if (!$pegawai_paket) {
                $pegawai_paket = new PegawaiPaket();
                $pegawai_paket->pegawai_id = $id;
                $pegawai_paket->paket_id = $value;
            } else {
                return redirect()->back()->with('error', 'Paket sudah ada di paket pegawai ini');
            }

            // Set komisi per paket
            $pegawai_paket->komisi_paket = $request->input('komisi_perpaket'); // pastikan array komisi_perpaket sinkron dengan paket_id

            // Simpan data
            $pegawai_paket->save();
        }

        return redirect()->back()->with('success', 'Data Paket Pegawai Berhasil Ditambahkan');
    }

    public function pegawaiPaketUpdate($id, Request $request)
    {
        $data = PegawaiPaket::find($id);
        $data->paket_id = $request->input('paket_id');
        $data->komisi_paket = $request->input('komisi_paket');
        $data->update();
        return redirect()->back()->with('success', 'Data Paket Pegawai Berhasil Diubah');
    }

    public function pegawaiPaketDestroy($id)
    {
        $data = PegawaiPaket::find($id);
        $data->delete();
        return redirect()->back()->with('success', 'Data Paket Pegawai Berhasil Dihapus');
    }
}
