<?php
require_once '../includes/config.php';
require_once 'helpers.php';
require_once 'smtp_mail.php';

$email = $_POST['email'] ?? '';
$otp   = $_POST['otp'] ?? '';

if ($email === '' || $otp === '') {
    jsAlert('Missing Information', 'Please enter the OTP code.', 'warning');
}

/* =========================
   FETCH USER
========================= */
$stmt = $conn->prepare("
    SELECT id, name, company_id, email_verified, otp_attempts
    FROM users
    WHERE email = ?
");
$stmt->bind_param("s", $email);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();

if (!$user) {
    jsAlert('User Not Found', 'No account found for this email address.', 'error', '../sign-up.php');
}

/* =========================
   BLOCK EXCESS ATTEMPTS
========================= */
if ($user['otp_attempts'] >= 5) {
    jsAlert(
        'Too Many Attempts',
        'You have exceeded the maximum OTP attempts. Please request a new verification code.',
        'error',
        "../verify-email.php?email=" . urlencode($email)
    );
}

/* =========================
   VERIFY OTP
========================= */
$stmt = $conn->prepare("
    SELECT id 
    FROM users
    WHERE email = ? 
      AND email_otp = ? 
      AND otp_expires >= NOW()
");
$stmt->bind_param("ss", $email, $otp);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows === 1) {

    /* =========================
       MARK EMAIL AS VERIFIED
    ========================= */
    $stmt = $conn->prepare("
        UPDATE users
        SET email_verified = 1,
            email_otp = NULL,
            otp_expires = NULL,
            otp_attempts = 0
        WHERE email = ?
    ");
    $stmt->bind_param("s", $email);
    $stmt->execute();

    /* =========================
       START FREE TRIAL (ONCE)
    ========================= */
    $company_id = (int) $user['company_id'];

    // Check if subscription already exists
    $stmt = $conn->prepare("
        SELECT id 
        FROM subscriptions 
        WHERE company_id = ?
        LIMIT 1
    ");
    $stmt->bind_param("i", $company_id);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows === 0) {

        // Create 30-day free trial
        $stmt = $conn->prepare("
            INSERT INTO subscriptions (
                company_id,
                plan,
                status,
                trial_started_at,
                trial_ends_at
            ) VALUES (
                ?, 'trial', 'trial',
                NOW(),
                DATE_ADD(NOW(), INTERVAL 30 DAY)
            )
        ");
        $stmt->bind_param("i", $company_id);
        $stmt->execute();
    }

    /* =========================
       SEND WELCOME EMAIL
    ========================= */
    sendWelcomeEmail($email, $user['name']);

    /* =========================
       SUCCESS MESSAGE
    ========================= */
    jsAlert(
        'Email Verified!',
        'Your account has been successfully verified. Your 30-day free trial has started.',
        'success',
        '../sign-in.php'
    );

} else {

    /* =========================
       INVALID OTP
    ========================= */
    $stmt = $conn->prepare("
        UPDATE users
        SET otp_attempts = otp_attempts + 1
        WHERE email = ?
    ");
    $stmt->bind_param("s", $email);
    $stmt->execute();

    $remaining = 5 - ($user['otp_attempts'] + 1);

    jsAlert(
        'Invalid OTP',
        "The OTP you entered is incorrect or has expired. Attempts remaining: {$remaining}",
        'warning'
    );
}
?>
