<?php
session_start();

$username = $_SESSION['username'] ?? '';
$database = $_SESSION['database'] ?? '';
$userid = $_SESSION['userid'] ?? '';

$message = '';
$showOTPForm = false;

require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';

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


try {
    require_once 'connection.php';
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

// Check if user already has email set
$query = $pdo->prepare('SELECT EMAIL FROM USERS WHERE USERID = ? AND USERNAME = ? AND DATABASENAME = ?');
$query->execute([$userid, $username, $database]);
$row = $query->fetch(PDO::FETCH_ASSOC);

if ($row && !is_null($row['EMAIL'])) {
    $_SESSION['username'] = $username;
    $_SESSION['database'] = $database;
    $_SESSION['userid'] = $userid;
    unset($_SESSION['otp'], $_SESSION['email']);
    header("Refresh:1; url=landing.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($row && is_null($row['EMAIL']) && isset($_POST['email'])) {
        $enteredEmail = $_POST['email'];

        // Check if email already exists
        $checkEmailQuery = $pdo->prepare('SELECT USERID FROM USERS WHERE EMAIL = ?');
        $checkEmailQuery->execute([$enteredEmail]);
        $checkResult = $checkEmailQuery->fetchAll();

        if (count($checkResult) > 0) {
            $message = "❌ Email Already in Use.";
        } else {
            $otp = rand(100000, 999999);
            $_SESSION['otp'] = $otp;
            $_SESSION['email'] = $enteredEmail;

            $mail = new PHPMailer(true);
            try {
                $mail->isSMTP();
                $mail->Host = 'smtp.gmail.com';
                $mail->SMTPAuth = true;
                $mail->Username = 'abhinavjindal19here@gmail.com';
                $mail->Password = 'wlhz lvsb ifcu qnhq';
                $mail->SMTPSecure = 'tls';
                $mail->Port = 587;

                $mail->setFrom('abhinavjindal19here@gmail.com', 'Abhinav Jindal');
                $mail->addAddress($enteredEmail);

                $mail->isHTML(false);
                $mail->Subject = 'Your OTP Code';
                $mail->Body = "Your OTP is: $otp\nThis OTP is valid for 5 minutes.";

                $mail->send();
                $message = "✅ OTP sent to " . htmlspecialchars($enteredEmail);
                $showOTPForm = true;
            } catch (Exception $e) {
                $message = "❌ Mail Error: " . $mail->ErrorInfo;
            }
        }
    } elseif (isset($_POST['otp'])) {
        if (!isset($_SESSION['otp'])) {
            $message = "⚠️ No OTP session found. Please request a new OTP.";
        } elseif ($_POST['otp'] == $_SESSION['otp']) {
            $message = "✅ OTP Verified Successfully!";

            // Update user's email
            $updateQuery = $pdo->prepare('UPDATE USERS SET EMAIL = ? WHERE USERID = ? AND USERNAME = ? AND DATABASENAME = ?');
            $updateQuery->execute([$_SESSION['email'], $userid, $username, $database]);

            $_SESSION['username'] = $username;
            $_SESSION['database'] = $database;
            $_SESSION['userid'] = $userid;
            unset($_SESSION['otp'], $_SESSION['email']);

            header("Refresh:2; url=landing.php");
            exit();
        } else {
            $message = "❌ Invalid OTP. Please try again.";
            $showOTPForm = true;
        }
    }
}
else if($username==="" || $database==="" || $userid===""){
    header("location: login.html");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>OTP Verification</title>
    <link rel="stylesheet" href="main.css">
</head>
<body class="send_otp_php">
    <h2>OTP Verification</h2>
    <p><?= $message ?></p>

    <?php if (!$showOTPForm && !isset($_SESSION['otp'])): ?>
        <!-- Email Form -->
        <form method="POST">
            <label>Email:</label>
            <input type="email" name="email" required>
            <button type="submit">Send OTP</button>
        </form>
    <?php else: ?>
        <!-- OTP Form -->
        <form method="POST">
            <label>Enter OTP:</label>
            <input type="number" name="otp" required>
            <button type="submit">Verify OTP</button>
        </form>
    <?php endif; ?>
</body>
</html>
