<?php
session_start();
require 'config.php';

if (!isset($_SESSION['pending_user'])) {
    header("Location: login.php");
    exit;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $otp = trim($_POST['otp']);
    $user_id = $_SESSION['pending_user'];

    $stmt = $conn->prepare("SELECT otp_code FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();

    if ($user && $user['otp_code'] == $otp) {
        $stmt = $conn->prepare("UPDATE users SET otp_verified = 1 WHERE id = ?");
        $stmt->bind_param("i", $user_id);
        $stmt->execute();

        $_SESSION['user_id'] = $user_id;
        unset($_SESSION['pending_user']);
        header("Location: my-dashboard.php");
        exit;
    } else {
        $error = "Invalid OTP code.";
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OTP Verification</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">
</head>
<body>

<div class="container d-flex justify-content-center align-items-center vh-100">
    <div class="card p-4" style="width: 400px;">
        <h4 class="mb-3">Verify OTP</h4>
        <?php if (isset($error)): ?>
            <div class="alert alert-danger"><?php echo $error; ?></div>
        <?php endif; ?>
        <form method="post">
            <label>Enter OTP</label>
            <input type="text" name="otp" class="form-control" required>

            <button type="submit" class="btn btn-success w-100 mt-3">Verify</button>
        </form>
    </div>
</div>

</body>
</html>
