<?php

namespace App\Http\Controllers;

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

class pelangganController 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', 'pelanggan')->get();
            $pelanggan = [];
            foreach ($data as $d) {
                $peg = Pelanggan::where('users_id', $d->id)->first();
                $pelanggan[] = $peg;
            }
        } elseif (Auth::user()->role == 'admin') {
            $akun = Auth::user()->id;
            $admin = Admin::where('users_id', $akun)->first();
            $admin_brand = $admin->brand_id;
            $pelanggan = Pelanggan::join('laundry', 'laundry.id', '=', 'pelanggan.laundry_id')
                ->where('laundry.brand_id', $admin_brand)
                ->get(['pelanggan.*', 'pelanggan.status as pegawai_status', 'laundry.status as laundry_status']);
            $laundry = Laundry::where('brand_id', $admin->brand_id)->get();
        } else {
            if (Auth::user()->role == 'pegawai') {
                $pegawai_on = Pegawai::where('users_id', Auth::user()->id)->first();
                $pelanggan = Pelanggan::where('laundry_id', $pegawai_on->laundry_id)->get();
                $laundry = Laundry::where('id', $pegawai_on->laundry_id)->first();
            } elseif (Auth::user()->role == 'kepala_toko') {
                $pegawai_on = KepalaToko::where('users_id', Auth::user()->id)->first();
                $pelanggan = Pelanggan::where('laundry_id', $pegawai_on->laundry_id)->get();
                $laundry = Laundry::where('id', $pegawai_on->laundry_id)->first();
            }
        }
        return view('pelanggan.index', compact('pelanggan', 'laundry'));
    }

    /**
     * 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' => 'pelanggan',

        ]);
        $user->save();

        $pegawai = new \App\Models\Pelanggan();
        $pegawai->users_id = $user->id;
        $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;
        } else {
            $pegawai->foto = 'default.png';
        }
        $pegawai->save();

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

    /**
     * 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($id)
    {
        if (Auth::user()->role == 'superadmin') {
            $akun = User::find($id);
            $data = Pelanggan::where('users_id', $id)->first();
            $laundry = Laundry::all();
        } elseif (Auth::user()->role == 'admin') {
            $akun = User::find($id);
            $data = Pelanggan::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();
        } else {
            $akun = User::find($id);
            $data = Pelanggan::where('users_id', $id)->first();
            $laundry = [];
            foreach ($data as $d) {
                $peg = Pelanggan::where('users_id', $d->id)->first();
                $laundry[] = $peg;
            }
        }
        return view('pelanggan.edit', compact('data', 'laundry'));
    }

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

        // Update data Pelanggan
        $pelanggan->laundry_id = $request->input('laundry_id');
        $pelanggan->nama = $request->input('nama');
        $pelanggan->alamat = $request->input('alamat');
        $pelanggan->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);
            $pelanggan->foto = $filename;
        }
        $pelanggan->update();

        $akun = User::find($pelanggan->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('/pelanggan')->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)
    {
        $pelanggan = Pelanggan::find($id);
        if ($pelanggan->status == 'aktif') {
            $pelanggan->status = 'tidak aktif';
        } else {
            $pelanggan->status = 'aktif';
        }
        $pelanggan->update();
        return redirect()->route('pelanggan.index')->with('success', 'Status pelanggan berhasil diubah');
    }
}
