<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Mews\Captcha\Facades\Captcha;
use App\Models\User;

use App\Models\UserUnitKerja;
use Yajra\DataTables\Facades\DataTables;

class AuthController extends Controller
{
    public function index()
    {


        //dd($user);
        return view('master.user.index');
    }

    public function create()
    {

        return view('master.user.create');
    }

    public function edit($id)
    {

        $user = User::findOrFail($id);
        return view('master.user.edit', compact('user'));
    }

    public function form_login()
    {
        $a = rand(1, 9);
        $b = rand(1, 9);

        // Simpan hasilnya ke session
        session(['captcha_result' => $a + $b]);
        // var_dump($a);
        // exit;
        //return view('form', compact('a', 'b'));

        return view('auth.login', compact('a', 'b'));
    }

    public function login(Request $request)
    {
        $user = User::all();

        //dd($user);
        // Validasi input termasuk CAPTCHA
        $validator = Validator::make($request->all(), [
            'username' => 'required',
            'password' => 'required',
            'captcha' => 'required|numeric',
        ]);

        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        if ($request->captcha != session('captcha_result')) {
            return back()->withErrors(['alert-danger' => 'Jawaban captcha salah!'])->withInput();
        }

        $credentials = $request->only('username', 'password');

        if (Auth::attempt($credentials)) {
            $request->session()->regenerate();
            return redirect()->intended('/home');
        }

        return back()->with('alert-danger', 'Login Failed!');
    }



    public function store(Request $request)
    {
        // Validasi input agar tidak ada data kosong atau tidak valid
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'username' => 'required|string|max:255|unique:users,username',
            'email' => 'required|email|max:255|unique:users,email', // Validasi email
            'no_hp' => 'required|string|max:15',
            'password' => 'required|string|min:6|confirmed'
        ]);
        //dd($validated);

        // Gunakan transaksi agar jika ada error, data tidak terpotong
        DB::beginTransaction();
        try {
            // 🔍 Cek apakah kode masuk ke sini
            $nama_image = null;
            if ($request->file('foto')) {
                $image = $request->file('foto');
                $nama_image = 'foto-' . uniqid() . '-' . $image->getClientOriginalName();
                $dir = 'img/foto';
                $image->move(public_path($dir), $nama_image);
            }
            // Buat user baru
            $user = User::create([
                'nama_lengkap' => $validated['name'],
                'username' => $validated['username'],
                'no_telp' => $validated['no_hp'],
                'email' => $validated['email'],
                'foto' => $nama_image,
                'password' => Hash::make($validated['password']),
                'pwd' => $validated['password'],
                'level' => $request->level
            ]);
            //exit;





            DB::commit(); // Simpan perubahan ke database

            return redirect('auth')->with('alert-success', 'Success Tambah Data');
        } catch (\Exception $e) {
            DB::rollBack(); // Batalkan jika ada kesalahan
            return back()->with('alert-failed', 'Gagal menambahkan data: ' . $e->getMessage());
        }
    }

    public function update(Request $request, $id)
    {
        // Validasi input
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'username' => 'required|string|max:255',
            'no_hp' => 'required|string|max:15',
            'password' => 'nullable|string|min:6|confirmed', // Bisa kosong

        ]);

        DB::beginTransaction();
        try {
            $user = User::findOrFail($id);
            $user->nama_lengkap = $validated['name'];
            $user->username = $validated['username'];
            $user->no_telp = $validated['no_hp'];
            $user->email = $request->input('email');
            $user->level = $request->input('level');

            // Proses foto
            if ($request->hasFile('foto')) {
                // Hapus foto lama jika ada
                if (!empty($user->foto) && file_exists(public_path('img/foto/' . $user->foto))) {
                    unlink(public_path('img/foto/' . $user->foto));
                }

                // Simpan foto baru
                $image = $request->file('foto');
                $nama_image = 'foto-' . uniqid() . '-' . $image->getClientOriginalName();
                $image->move(public_path('img/foto'), $nama_image);
                $user->foto = $nama_image;
            }

            // Update password hanya jika diisi
            if (!empty($validated['password'])) {
                $user->pwd = $validated['password'];
                $user->password = Hash::make($validated['password']);
            }

            $user->save();



            DB::commit();
            return redirect()->route('auth.index')->with('alert-success', 'User updated successfully');
        } catch (\Exception $e) {
            DB::rollBack();
            return back()->with('alert-failed', 'Gagal memperbarui data: ' . $e->getMessage());
        }
    }



    public function logout()
    {
        Auth::logout();
        return redirect('/');
    }

    public function destroy($id)
    {
        User::findOrFail($id)->delete();


        return redirect('auth')->with('alert-success', 'Success deleted data');
    }

    public function getData(Request $request)
    {
        if ($request->ajax()) {
            $data = User::select(
                'users.*',

            )

                ->orderBy('users.id', 'desc')
                ->get()
                ->map(function ($item) {
                    return $item;
                });

            //dd($data);


            return Datatables::of($data)
                ->addColumn('action', function ($row) {
                    $editRoute = route('auth.edit', ['auth' => $row->id]);

                    //$showRoute = route('auth.show', ['auth' => $row->id]);
                    $deleteRoute = route('auth.destroy', ['auth' => $row->id]);
                    $btn = '<form method="POST" action="' . $deleteRoute . '" style="margin-left: 10px;" onsubmit="return confirm(\'Apakah anda yakin?\')">';
                    $btn .= '<div class="btn-group">';
                    //$btn .= '<a href="' . $showRoute . '" class="btn btn-success ml-2">Detail</a>';


                    $btn .= '<a href="' . $editRoute . '" class="btn btn-warning">Edit</a>';
                    $btn .= '<button type="submit" class="btn btn-danger ml-2">Hapus</button>';
                    $btn .= csrf_field(); // Blade directive for CSRF token
                    $btn .= method_field("DELETE"); // Blade directive for HTTP method spoofing

                    $btn .= '</div>';
                    $btn .= '</form>';

                    return $btn;
                })
                ->rawColumns(['action'])
                ->make(true);
        }
    }
}
