<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require_once "config/database.php";
require_once __DIR__ . '/vendor/autoload.php';
require_once "includes/send_mail.php";

$database = new Database();
$db = $database->getConnection();

if (!$db) {
    die("Database connection failed.");
}

$message = "";
$message_type = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $login_id = trim($_POST['login_id'] ?? '');

    if ($login_id === '') {
        $message = "Please enter your username or email.";
        $message_type = "error";
    } else {
        $stmt = $db->prepare("
            SELECT id, full_name, email
            FROM users
            WHERE (username = :login_id OR email = :login_id)
              AND status = 'active'
            LIMIT 1
        ");
        $stmt->bindParam(":login_id", $login_id);
        $stmt->execute();
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        // Always show same message for security
        $message = "If the account exists, a password reset link has been sent to the email address.";
        $message_type = "success";

        if ($user) {
            $token = bin2hex(random_bytes(32));
            $hashedToken = hash('sha256', $token);
            $expiresAt = date('Y-m-d H:i:s', strtotime('+1 hour'));

            $insert = $db->prepare("
                INSERT INTO password_resets (user_id, token, expires_at, used)
                VALUES (:user_id, :token, :expires_at, 0)
            ");
            $insert->bindParam(":user_id", $user['id']);
            $insert->bindParam(":token", $hashedToken);
            $insert->bindParam(":expires_at", $expiresAt);
            $insert->execute();

            $baseUrl = "https://www.sevendigital.shop/dms";
            $resetLink = $baseUrl . "/reset_password.php?token=" . urlencode($token);

            $subject = "Password Reset Request";

            $bodyHtml = "
                <p>Hello " . htmlspecialchars($user['full_name']) . ",</p>
                <p>We received a request to reset your password.</p>
                <p>
                    <a href='" . htmlspecialchars($resetLink) . "' style='
                        display:inline-block;
                        padding:12px 18px;
                        background:#2563eb;
                        color:#ffffff;
                        text-decoration:none;
                        border-radius:8px;
                        font-weight:600;
                    '>Reset Password</a>
                </p>
                <p>Or copy this link into your browser:</p>
                <p>" . htmlspecialchars($resetLink) . "</p>
                <p>This link will expire in 1 hour.</p>
                <p>If you did not request this, please ignore this email.</p>
            ";

            $bodyText = "Hello " . $user['full_name'] . "\n\n"
                . "We received a request to reset your password.\n"
                . "Reset link: " . $resetLink . "\n\n"
                . "This link will expire in 1 hour.\n"
                . "If you did not request this, please ignore this email.";

            $mailResult = sendMail(
                $user['email'],
                $user['full_name'],
                $subject,
                $bodyHtml,
                $bodyText
            );

            if ($mailResult !== true) {
                error_log("Mail send failed: " . $mailResult);
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Forgot Password - DocuTrack</title>
    <style>
        body {
            margin: 0;
            background: linear-gradient(135deg, #f4f7fb 0%, #e9eef6 100%);
            font-family: Arial, sans-serif;
        }

        .page {
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 24px;
        }

        .card {
            width: 100%;
            max-width: 420px;
            background: #fff;
            padding: 32px;
            border-radius: 20px;
            box-shadow: 0 20px 50px rgba(16, 24, 40, 0.12);
        }

        h2 {
            margin-top: 0;
            margin-bottom: 8px;
        }

        p.subtext {
            color: #667085;
            margin-bottom: 24px;
        }

        .form-group {
            margin-bottom: 18px;
        }

        .form-group label {
            display: block;
            font-weight: 600;
            margin-bottom: 8px;
            color: #344054;
        }

        .form-group input {
            width: 100%;
            box-sizing: border-box;
            padding: 12px 14px;
            border: 1px solid #d0d5dd;
            border-radius: 12px;
            font-size: 15px;
        }

        .alert-box {
            margin-bottom: 18px;
            padding: 12px 14px;
            border-radius: 12px;
            font-size: 14px;
        }

        .alert-danger {
            background: #fef3f2;
            color: #b42318;
            border: 1px solid #fecdca;
        }

        .alert-success {
            background: #ecfdf3;
            color: #166534;
            border: 1px solid #abefc6;
        }

        button {
            width: 100%;
            padding: 12px 14px;
            border: none;
            border-radius: 12px;
            background: #2563eb;
            color: white;
            font-size: 15px;
            cursor: pointer;
        }

        .back-link {
            display: block;
            text-align: center;
            margin-top: 16px;
            color: #2563eb;
            text-decoration: none;
            font-weight: 600;
        }
    </style>
</head>
<body>
    <div class="page">
        <div class="card">
            <h2>Forgot Password</h2>
            <p class="subtext">Enter your username or email and we will send a reset link to your email.</p>

            <?php if ($message !== ""): ?>
                <div class="alert-box <?php echo $message_type === 'success' ? 'alert-success' : 'alert-danger'; ?>">
                    <?php echo htmlspecialchars($message); ?>
                </div>
            <?php endif; ?>

            <form method="POST">
                <div class="form-group">
                    <label for="login_id">Username or Email</label>
                    <input
                        type="text"
                        name="login_id"
                        id="login_id"
                        value="<?php echo htmlspecialchars($_POST['login_id'] ?? ''); ?>"
                        placeholder="Enter your username or email"
                        required
                    >
                </div>

                <button type="submit">Send Reset Link</button>
            </form>

            <a href="login.php" class="back-link">Back to Login</a>
        </div>
    </div>
</body>
</html>