<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Carbon\Carbon;

class PasswordResetController extends Controller
{
    public function showLinkRequestForm()
    {
        return view('auth.forgot-password');
    }

    public function sendResetLinkEmail(Request $request)
    {
        $request->validate(['email' => 'required|email']);

        $user = User::where('email', $request->email)->first();

        // Cek jika akun ada
        if (!$user) {
            return back()->withErrors(['email' => 'Email tidak ditemukan']);
        }
        // Syarat utama: HANYA Admin yang boleh melakukan reset
        if ($user->role !== 'admin') {
            return back()->withErrors(['email' => 'Fitur Lupa Password HANYA tersedia untuk Admin. Karyawan harap menghubungi Admin.']);
        }

        // Generate token
        $token = Str::random(60);

        // Hapus token lama jika ada, lalu insert yang baru (menyederhanakan karena kita bisa pakai insert)
        DB::table('password_resets')->where('email', $user->email)->delete();
        DB::table('password_resets')->insert([
            'email' => $user->email,
            'token' => Hash::make($token),
            'created_at' => Carbon::now()
        ]);

        // Buat link reset
        $resetUrl = url('/reset-password/' . $token . '?email=' . urlencode($user->email));

        // Mengirim Email
        // Pastikan driver mail di-set ke 'log' pada .env agar bisa dilihat di storage/logs/laravel.log pada local environment.
        Mail::raw("Halo Admin,\n\nSilakan klik tautan di bawah ini untuk mereset kata sandi akun Anda:\n{$resetUrl}\n\nJika Anda tidak merasa mengajukan permintaan ini, mohon abaikan pesan ini.", function ($message) use ($user) {
            $message->to($user->email)
                    ->subject('Reset Password Sistem Akuntansi Cak Imin');
        });

        return back()->with('status', 'Link reset password telah dikirim ke email Anda. Silakan cek inbox/spam Anda.');
    }

    public function showResetForm($token, Request $request)
    {
        return view('auth.reset-password', ['token' => $token, 'email' => $request->email]);
    }

    public function reset(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required|min:6|confirmed',
            'token' => 'required'
        ]);

        // Verifikasi token
        $resetRecord = DB::table('password_resets')->where('email', $request->email)->first();

        if (!$resetRecord || !Hash::check($request->token, $resetRecord->token)) {
            return back()->withErrors(['token' => 'Token reset kadaluarsa atau tidak valid. Harap minta kembali link reset.']);
        }

        // Verifikasi User Admin
        $user = User::where('email', $request->email)->first();
        if (!$user || $user->role !== 'admin') {
            return back()->withErrors(['email' => 'Akses ditolak. Fitur reset hanya dapat diakses oleh Admin.']);
        }

        // Update Password
        $user->password = Hash::make($request->password);
        $user->save();

        // Hapus Token Reset
        DB::table('password_resets')->where('email', $request->email)->delete();

        return redirect('/login')->with('success', 'Berhasil! Kata sandi telah diubah. Silakan masuk menggunakan kata sandi baru.');
    }
}
