<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require '../vendor/phpmailer/phpmailer/src/PHPMailer.php';
require '../vendor/phpmailer/phpmailer/src/SMTP.php';
require '../vendor/phpmailer/phpmailer/src/Exception.php';
require '../config.php';

$email = $_POST['email'];
$cek = mysqli_query($conn, "SELECT * FROM pengguna WHERE email='$email'");

if (mysqli_num_rows($cek) > 0) {
    $token = bin2hex(random_bytes(16));
    mysqli_query($conn, "UPDATE pengguna SET reset_token='$token' WHERE email='$email'");

    $link_reset = "http://localhost/day.apparel/reset/reset_password.php?token=$token";

    // Kirim email
    $mail = new PHPMailer(true);
    try {
        // Konfigurasi SMTP
        $mail->isSMTP();    
        $mail->Host = 'dayapparel.my.id;103.16.198.177'; // ganti sesuai SMTP kamu (tidak usah di ubah karena gmail)
        $mail->SMTPAuth = true;
        $mail->Username =  'otp@dayapparel.my.id'; // ganti
        $mail->Password = 'dayaperral123';     // gunakan app password Gmail
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        // Pengirim dan penerima
        $mail->setFrom('otp@dayapparel.my.id', 'Day.Apparel');
        $mail->addAddress($email);

        // Konten email
        $mail->isHTML(true);
        $mail->Subject = 'Reset Password Akun Anda';
        $mail->Body    = "Klik link berikut untuk mereset password Anda: <br><a href='$link_reset'>$link_reset</a>";

        $mail->send();
        header("Location: ../lupa_password.php?pesan=Email reset sudah dikirim.");
    } catch (Exception $e) {
        header("Location: ../lupa_password.php?pesan=Gagal kirim email: {$mail->ErrorInfo}");
    }

} else {
    header("Location: ../lupa_password.php?pesan=Email tidak ditemukan.");
}
