<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Hash;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Support\Str;
use App\Models\User;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;

class ForgotPasswordController extends BaseController
{
    /**
     * Send reset password link
     */
    public function sendResetLinkEmail(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email',
        ]);

        if ($validator->fails()) {
            return $this->sendError('Error validasi.', $validator->errors(), 422);
        }

        // Check if user exists and has the correct role based on the endpoint
        $user = User::where('email', $request->email)->first();
        $path = request()->path();
        $requiredRole = str_contains($path, 'penjahit') ? 'penjahit' : 'pelanggan';

        if (!$user || $user->role !== $requiredRole) {
            return $this->sendError('Error.', ['email' => 'Email tidak ditemukan'], 404);
        }

        // Generate 6-digit PIN
        $pin = str_pad(random_int(0, 999999), 6, '0', STR_PAD_LEFT);

        // Store PIN in password_resets table
        DB::table('password_resets')->updateOrInsert(
            ['email' => $user->email],
            [
                'token' => $pin,
                'created_at' => Carbon::now()
            ]
        );

        // Send custom reset password email with PIN
        $user->notify(new \App\Notifications\ResetPasswordNotification($pin));

        return $this->sendResponse([
            'message' => 'PIN reset password telah dikirim ke email Anda'
        ], 'Kami sudah mengirim PIN reset password ke email Anda');
    }

    /**
     * Reset password
     */
    public function reset(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'pin' => 'required|digits:6',
            'email' => 'required|email',
            'password' => 'required|confirmed|min:8',
        ]);

        if ($validator->fails()) {
            return $this->sendError('Error validasi.', $validator->errors(), 422);
        }

        // Check if user exists and has the correct role based on the endpoint
        $user = User::where('email', $request->email)->first();
        $path = request()->path();
        $requiredRole = str_contains($path, 'penjahit') ? 'penjahit' : 'pelanggan';

        if (!$user || $user->role !== $requiredRole) {
            return $this->sendError('Error.', ['email' => 'Email tidak ditemukan'], 404);
        }

        // Check if PIN exists and is valid
        $passwordReset = DB::table('password_resets')
            ->where('email', $user->email)
            ->where('token', $request->pin)
            ->first();

        if (!$passwordReset) {
            return $this->sendError('Error.', ['pin' => 'PIN tidak valid atau sudah kadaluarsa'], 400);
        }

        // Check if PIN is expired (60 minutes)
        $createdAt = Carbon::parse($passwordReset->created_at);
        if ($createdAt->addMinutes(60)->isPast()) {
            DB::table('password_resets')->where('email', $user->email)->delete();
            return $this->sendError('Error.', ['pin' => 'PIN sudah kadaluarsa'], 400);
        }

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

        // Delete PIN
        DB::table('password_resets')->where('email', $user->email)->delete();

        // Fire password reset event
        event(new PasswordReset($user));

        return $this->sendResponse([], 'Password berhasil direset');
    }

    /**
     * Generate reset password URL
     */
    protected function generateResetUrl($user, $token)
    {
        // Get frontend URL from config or env
        $frontendUrl = config('app.frontend_url', env('FRONTEND_URL', 'http://localhost:3000'));

        // Combine with frontend URL
        return $frontendUrl . '/reset-password?email=' . urlencode($user->email) . '&token=' . $token;
    }
}
