<?php
session_start();
require_once '../src/Database.php';
require_once __DIR__ . '/../PHPMailer-master/send-mail.php';

$conne = Database::getInstance();

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

    // Prepare SELECT query
    $stmt = $conne->prepare("SELECT id FROM users WHERE email = ?");
    if (!$stmt) {
        die("Prepare failed: " . $conne->error);
    }
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();

    if ($user) {
        $token = bin2hex(random_bytes(16));
        $expiry = date('Y-m-d H:i:s', time() + 3600);

        // Prepare UPDATE query
        $stmt = $conne->prepare("UPDATE users SET reset_token = ?, token_expiry = ? WHERE email = ?");
        if (!$stmt) {
            die("Prepare failed: " . $conne->error);
        }
        $stmt->bind_param('sss', $token, $expiry, $email);
        $stmt->execute();
        $stmt->close();

        $resetLink = "http://localhost/help/helpdesk-core-php/ticket-user/new-password.php?token=$token";
        $subject = "Password Reset Request";
        $body = "Hello,<br><br>Please click the link below to reset your password:<br>
                 <a href='$resetLink'>$resetLink</a><br><br>This link will expire in 1 hour.<br><br>Thanks,<br>Helpdesk Team";

        if (sendMail($email, '', $subject, $body)) {
            $_SESSION['message'] = "Password reset link sent to your email.";
        } else {
            $_SESSION['error'] = "Failed to send email.";
        }
    } else {
        $_SESSION['error'] = "Email not found.";
    }

    header("Location: login-reg.php?box=reset");
    exit;
}
