<?php
/**
 * OTP Management Helper
 */

/**
 * Generate a random 6-digit OTP
 */
function generateOTP($length = 6) {
    $otp = '';
    for ($i = 0; $i < $length; $i++) {
        $otp .= random_int(0, 9);
    }
    return $otp;
}

/**
 * Store OTP in database
 */
function storeOTP($email, $otp, $purpose = 'verification', $expiryMinutes = 10) {
    global $conn;

    try {
        $expiryTime = date('Y-m-d H:i:s', time() + ($expiryMinutes * 60));
        
        // Delete any existing OTP for this email
        $deleteStmt = $conn->prepare("DELETE FROM otp_verifications WHERE email = ? AND purpose = ?");
        if ($deleteStmt) {
            $deleteStmt->bind_param('ss', $email, $purpose);
            $deleteStmt->execute();
            $deleteStmt->close();
        }

        // Insert new OTP
        $insertStmt = $conn->prepare("INSERT INTO otp_verifications (email, otp, purpose, expires_at, created_at, is_used) VALUES (?, ?, ?, ?, NOW(), 0)");
        if ($insertStmt) {
            $insertStmt->bind_param('ssss', $email, $otp, $purpose, $expiryTime);
            $result = $insertStmt->execute();
            $insertStmt->close();
            return $result;
        }
        return false;
    } catch (Exception $e) {
        error_log('OTP Storage Error: ' . $e->getMessage());
        return false;
    }
}

/**
 * Verify OTP
 */
function verifyOTP($email, $otp, $purpose = 'verification') {
    global $conn;

    try {
        $stmt = $conn->prepare("
            SELECT id, otp, expires_at, is_used 
            FROM otp_verifications 
            WHERE email = ? AND purpose = ? 
            ORDER BY created_at DESC 
            LIMIT 1
        ");

        if (!$stmt) {
            return ['success' => false, 'message' => 'Database error'];
        }

        $stmt->bind_param('ss', $email, $purpose);
        $stmt->execute();
        $result = $stmt->get_result();
        $otpRecord = $result ? $result->fetch_assoc() : null;
        $stmt->close();

        if (!$otpRecord) {
            return ['success' => false, 'message' => 'OTP not found'];
        }

        if ($otpRecord['is_used']) {
            return ['success' => false, 'message' => 'OTP already used'];
        }

        $now = new DateTime();
        $expiryTime = new DateTime($otpRecord['expires_at']);

        if ($now > $expiryTime) {
            return ['success' => false, 'message' => 'OTP has expired'];
        }

        if ($otpRecord['otp'] !== $otp) {
            return ['success' => false, 'message' => 'Invalid OTP'];
        }

        // Mark OTP as used
        $updateStmt = $conn->prepare("UPDATE otp_verifications SET is_used = 1 WHERE id = ?");
        if ($updateStmt) {
            $id = $otpRecord['id'];
            $updateStmt->bind_param('i', $id);
            $updateStmt->execute();
            $updateStmt->close();
        }

        return ['success' => true, 'message' => 'OTP verified successfully'];
    } catch (Exception $e) {
        error_log('OTP Verification Error: ' . $e->getMessage());
        return ['success' => false, 'message' => 'Verification failed'];
    }
}

/**
 * Check if OTP table exists, create if not
 */
function ensureOTPTable() {
    global $conn;

    $checkTable = $conn->query("SHOW TABLES LIKE 'otp_verifications'");
    
    if ($checkTable && $checkTable->num_rows > 0) {
        return true;
    }

    $createTableSQL = "
        CREATE TABLE IF NOT EXISTS otp_verifications (
            id INT AUTO_INCREMENT PRIMARY KEY,
            email VARCHAR(255) NOT NULL,
            otp VARCHAR(10) NOT NULL,
            purpose VARCHAR(50) NOT NULL DEFAULT 'verification',
            expires_at DATETIME NOT NULL,
            is_used TINYINT(1) DEFAULT 0,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
            INDEX idx_email_purpose (email, purpose),
            INDEX idx_expires_at (expires_at)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
    ";

    return $conn->query($createTableSQL);
}

// Ensure OTP table exists on every request
ensureOTPTable();

?>
