<?php
// PHPMailer classes को global namespace में इम्पोर्ट करें
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// config.php और PHPMailer की ज़रूरी फाइलों को शामिल करें
require_once 'config.php';
require 'PHPMailer-master/src/Exception.php';
require 'PHPMailer-master/src/PHPMailer.php';
require 'PHPMailer-master/src/SMTP.php';

$message = '';
$message_type = '';

if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['email'])) {
    $email = $_POST['email'];

    $stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows == 1) {
        $user = $result->fetch_assoc();
        $user_id = $user['id'];

        $token = bin2hex(random_bytes(50));
        $expires = new DateTime('NOW');
        $expires->add(new DateInterval('PT1H')); // 1 घंटे के लिए वैध
        $expires_str = $expires->format('Y-m-d H:i:s');

        $update_stmt = $conn->prepare("UPDATE users SET reset_token = ?, reset_token_expires_at = ? WHERE id = ?");
        $update_stmt->bind_param("ssi", $token, $expires_str, $user_id);
        $update_stmt->execute();

        $mail = new PHPMailer(true);
        try {
            //Server settings
            $mail->isSMTP();
            $mail->Host       = 'digifytech.in';
            $mail->SMTPAuth   = true;
            $mail->Username   = 'list@digifytech.in';
            $mail->Password   = 'Digify@123';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            $mail->Port       = 465;

            //Recipients
            $mail->setFrom('list@digifytech.in', 'Digify OS Support');
            $mail->addAddress($email);

            //Content
            $reset_link = "http://kids.eventsnews.in/reset-password.php?token=" . $token;
            $mail->isHTML(true);
            $mail->Subject = 'Password Reset Request for Digify OS';
            $mail->Body    = "Hello,<br><br>Please click on the link below to reset your password. This link is valid for 1 hour.<br><br><a href='{$reset_link}'>Reset Password</a><br><br>If you did not request this, please ignore this email.";
            
            $mail->send();
            $message = 'A password reset link has been sent to your email address.';
            $message_type = 'success';
        } catch (Exception $e) {
            $message = "Message could not be sent. Please contact support. Mailer Error: {$mail->ErrorInfo}";
            $message_type = 'error';
        }

    } else {
        $message = 'If an account with that email exists, a reset link has been sent.';
        $message_type = 'success';
    }
    $stmt->close();
    $conn->close();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password - Digify OS</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 flex items-center justify-center h-screen">
    <div class="w-full max-w-md bg-white rounded-lg shadow-md p-8">
        <h2 class="text-2xl font-bold text-center text-gray-800 mb-6">Reset Your Password</h2>
        
        <?php if (!empty($message)): ?>
            <div class="mb-4 p-4 rounded <?php echo ($message_type == 'success') ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'; ?>">
                <?php echo htmlspecialchars($message); ?>
            </div>
        <?php endif; ?>

        <form method="POST" action="forgot-password.php">
            <p class="text-sm text-gray-600 mb-4">Enter your email address and we will send you a link to reset your password.</p>
            <div>
                <label for="email" class="block text-sm font-medium text-gray-700">Email Address</label>
                <input id="email" type="email" name="email" required autofocus class="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm">
            </div>
            <div class="flex items-center justify-end mt-6">
                <button type="submit" class="w-full inline-flex items-center justify-center px-4 py-2 bg-blue-600 border border-transparent rounded-md font-semibold text-white hover:bg-blue-700">
                    Send Reset Link
                </button>
            </div>
             <div class="text-center mt-4">
                <a href="login.php" class="text-sm text-blue-600 hover:underline">Back to Login</a>
            </div>
        </form>
    </div>
</body>
</html>