📂 File Browser

//AgentAI
🌙 Dark Mode
🎯 Quick Launch:

📁 Directories

📁 tmp/ 🔓 Open
📁 vendor/ 🔓 Open

📄 Files

🐘 chat_handler.php
▶ Open 📄 View Source
📄 composer.json
▶ Open 📄 View Source
🐘 debug_emails.php
▶ Open 📄 View Source
🐘 fetch_emails.php
▶ Open 📄 View Source
🐘 get_email.php
▶ Open 📄 View Source
🐘 index.php
▶ Open 📄 View Source
🐘 logout.php
▶ Open 📄 View Source
🐘 oauth2callback.php
▶ Open 📄 View Source
🐘 test_api.php
▶ Open 📄 View Source

📄 Source: chat_handler.php

<?php
date_default_timezone_set('Europe/Bucharest');
session_start();
require_once 'vendor/autoload.php';

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

if (!isset($_SESSION['access_token'])) {
    http_response_code(401);
    echo json_encode(['reply' => 'Te rog să te autentifici mai întâi']);
    exit();
}

$input = json_decode(file_get_contents('php://input'), true);
$query = $input['query'] ?? '';

if (empty($query)) {
    echo json_encode(['reply' => 'Ce dorești să afli despre emailurile tale?']);
    exit();
}

// Fetch recent emails - 15 emails
$client = new Google\Client();
$client->setAccessToken($_SESSION['access_token']);
$service = new Google\Service\Gmail($client);

$optParams = ['maxResults' => 15, 'labelIds' => ['INBOX']];
$messages = $service->users_messages->listUsersMessages('me', $optParams);

$emailContext = [];
$emailListForDisplay = [];

if ($messages->getMessages()) {
    $index = 1;
    foreach ($messages->getMessages() as $msg) {
        $message = $service->users_messages->get('me', $msg->getId(), [
            'format' => 'metadata', 
            'metadataHeaders' => ['From', 'Subject', 'Date']
        ]);
        
        $headers = $message->getPayload()->getHeaders();
        $from = 'Unknown';
        $subject = '(no subject)';
        $date = 'Unknown date';
        
        foreach ($headers as $header) {
            if ($header->getName() == 'From') $from = $header->getValue();
            if ($header->getName() == 'Subject') $subject = $header->getValue();
            if ($header->getName() == 'Date') $date = $header->getValue();
        }
        
        // Convert to Romanian time
        try {
            $dateObj = new DateTime($date);
            $dateObj->setTimezone(new DateTimeZone('Europe/Bucharest'));
            $dateRomanian = $dateObj->format('d M Y, H:i');
        } catch (Exception $e) {
            $dateRomanian = $date;
        }
        
        $emailContext[] = "$index. De la: $from | Subiect: $subject | Primit: $dateRomanian";
        $emailListForDisplay[] = [
            'index' => $index,
            'from' => htmlspecialchars($from),
            'subject' => htmlspecialchars($subject),
            'date' => $dateRomanian
        ];
        $index++;
    }
}

$totalEmails = count($emailContext);
$emailSummary = implode("\n", $emailContext);

// OpenRouter API call
$openRouterKey = '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';
$url = 'https://openrouter.ai/api/v1/chat/completions';

$prompt = "Ești un asistent de emailuri care vorbește ROMÂNĂ. Iată ultimele $totalEmails emailuri din inbox:\n\n$emailSummary\n\nUtilizatorul întreabă: '$query'\n\nRăspunde DOAR pe baza acestor emailuri. Dacă utilizatorul cere mai multe emailuri decât există ($totalEmails), spune-i exact câte are. Folosește diacritice (ă,â,î,ș,ț). Fii concis dar completează răspunsul.";

$data = [
    'model' => 'openrouter/auto',
    'messages' => [
        ['role' => 'system', 'content' => 'Ești un asistent de email util. Vorbești doar română cu diacritice. Răspunzi doar pe baza emailurilor primite. Nu tăia răspunsurile.'],
        ['role' => 'user', 'content' => $prompt]
    ],
    'temperature' => 0.3,
    'max_tokens' => 1000
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 45);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Authorization: Bearer ' . $openRouterKey
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($httpCode == 200) {
    $result = json_decode($response, true);
    $reply = $result['choices'][0]['message']['content'] ?? "Nu am putut procesa cererea.";
} else {
    $reply = "Serviciul AI este temporar indisponibil. Te rog să încerci din nou.";
}

echo json_encode([
    'reply' => $reply,
    'emails' => $emailListForDisplay
]);
?>
← Back