<?php
session_start(); // Mula sesi

include('conn.php');  

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

require __DIR__ . '/vendor/autoload.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!empty($_POST['email'])) {
        $email = $_POST['email'];  

        // Semak jika email wujud dalam database
        $stmt_check_email = $conn->prepare("SELECT id FROM users WHERE email = ?");
        $stmt_check_email->bind_param("s", $email);
        $stmt_check_email->execute();
        $result_email = $stmt_check_email->get_result();

        if ($result_email->num_rows == 0) {
            $_SESSION['error'] = "Email tidak wujud dalam sistem.";
            header("Location: forgot_password.php");
            //echo"Email tidak wujud!!";
            exit();
        } else {
            $user = $result_email->fetch_assoc();
            $user_id = $user['id']; // Dapatkan user_id berdasarkan email

            // Kemaskini token tamat tempoh
            $current_time = date('Y-m-d H:i:s');
            $stmt_update_expired = $conn->prepare("UPDATE password_resets SET status = 0 WHERE expiry <= ?");
            $stmt_update_expired->bind_param("s", $current_time);
            $stmt_update_expired->execute();

            // Semak token aktif
            $stmt_check_token = $conn->prepare("SELECT * FROM password_resets WHERE user_id = ? AND status = 1");
            $stmt_check_token->bind_param("i", $user_id);
            $stmt_check_token->execute();
            $result_token = $stmt_check_token->get_result();

            if ($result_token->num_rows > 0) {
                $_SESSION['error'] = "Token telah dihantar. Sila semak e-mel anda.";
                header("Location: forgot_password.php");
                //echo"Token telah dihantar. Sila semak e-mel anda.";
                exit();
            }

            // Jika tiada token aktif, generate token baru
            $token = getToken(24); 
            $expiry = date('Y-m-d H:i:s', strtotime('+1 hour'));
            $created_at = date('Y-m-d H:i:s');
            $status = 1;

            // Masukkan token baru
            $stmt_insert_token = $conn->prepare("INSERT INTO password_resets (user_id, email, token, expiry, created_at, status) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt_insert_token->bind_param("issssi", $user_id, $email, $token, $expiry, $created_at, $status);

            if ($stmt_insert_token->execute()) {
                // Hantar e-mel
                $resetLink = "https://spnr.zakatpenang.com/views/resetpassword.php?token=" . urlencode($token) . "&user_id=" . $user_id;
                $subject = "Reset Kata Laluan Anda";
                $message = "Salam,<br><br>Klik pautan berikut untuk reset kata laluan anda:<br><a href='$resetLink'>$resetLink</a><br><br>Pautan ini akan tamat dalam masa 1 jam.<br><br>Terima kasih.";

                $mail = new PHPMailer(true);
                try {
                    $mail->isSMTP();
                    $mail->Host = 'spnr.zakatpenang.com';
                    $mail->SMTPAuth = true;
                    $mail->Username = 'admin@spnr.zakatpenang.com';
                    $mail->Password = 'Zakat@zpp123';
                    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                    $mail->Port = 465;

                    $mail->setFrom('admin@spnr.zakatpenang.com', 'Admin SPNR');
                    $mail->addAddress($email, 'Pengguna SPNR');

                    $mail->isHTML(true);
                    $mail->Subject = $subject;
                    $mail->Body = $message;
                    $mail->AltBody = "Salam,\n\nKlik pautan berikut untuk reset kata laluan anda:\n$resetLink\n\nPautan ini akan tamat dalam masa 1 jam.\n\nTerima kasih.";

                    $mail->send();
                    //echo"email sent";
                    $_SESSION['success'] = "Sila semak email anda untuk reset kata laluan.";
                    header("Location: forgot_password.php");
                } catch (Exception $e) {
                    $_SESSION['error'] = "Email gagal dihantar. Ralat: {$mail->ErrorInfo}";
                }
            } else {
                $_SESSION['error'] = "Ralat semasa menyimpan token: " . $stmt_insert_token->error;
                header("Location: forgot_password.php");
                exit();
            }
            $stmt_insert_token->close();
        }

        $stmt_check_email->close();
    } else {
        $_SESSION['error'] = "Sila isi email terlebih dahulu.";
        header("Location: forgot_password.php"); 
        exit();
    }
}

function getToken($length)
{
    $token = "";
    $codeAlphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    $max = strlen($codeAlphabet);

    for ($i = 0; $i < $length; $i++) {
        $token .= $codeAlphabet[crypto_rand_secure(0, $max - 1)];
    }

    return $token;
}

function crypto_rand_secure($min, $max)
{
    $range = $max - $min;
    if ($range < 1) return $min;
    $log = ceil(log($range, 2));
    $bytes = (int) ($log / 8) + 1;
    $bits = (int) $log + 1;
    $filter = (int) (1 << $bits) - 1;
    do {
        $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));
        $rnd = $rnd & $filter;
    } while ($rnd > $range);
    return $min + $rnd;
}
?>