<?php
declare(strict_types=1);
require_once dirname(__DIR__) . '/_bootstrap.php';
golder_require_method('POST');

$ctx = golder_api_auth('desktop_sync');
$master = $ctx['master'];
$customerId = (int)$ctx['customer_id'];

// Musterinin AI yetkisi var mi?
$stCheck = $master->prepare("SELECT is_ai_enabled FROM customers WHERE id = ?");
$stCheck->execute([$customerId]);
if ((int)$stCheck->fetchColumn() !== 1) {
    golder_json_error(403, 'AI_DISABLED', 'Yapay zeka asistani bu hesap icin aktif degil.');
}

$input = golder_api_input();
$messages = $input['messages'] ?? [];
$isNewQuestion = !empty($input['is_new_question']);
$activeProfileId = trim((string)($input['profile_id'] ?? ''));

if (!is_array($messages) || empty($messages)) {
    golder_json_error(400, 'INVALID_REQUEST', 'Messages array is required.');
}

// LIMIT KONTROLU (Gunde 100 Soru)
$today = date('Y-m-d');
$st = $master->prepare("SELECT question_count FROM ai_usage_logs WHERE customer_id = ? AND usage_date = ?");
$st->execute([$customerId, $today]);
$usageRow = $st->fetch();
$currentCount = $usageRow ? (int)$usageRow['question_count'] : 0;

if ($isNewQuestion) {
    if ($currentCount >= 100) {
        golder_json_error(429, 'LIMIT_REACHED', 'Gunluk 100 yapay zeka soru limitinize ulastiniz.');
    }
    $master->prepare("INSERT INTO ai_usage_logs (customer_id, usage_date, question_count) VALUES (?, ?, 1) ON DUPLICATE KEY UPDATE question_count = question_count + 1")->execute([$customerId, $today]);
}

// SEMAYI DOSYADAN OKU
$schemaPath = __DIR__ . '/ai_schema.sql';
$schemaDefinition = file_exists($schemaPath) ? file_get_contents($schemaPath) : "Sema bulunamadi.";

// BUGUNUN TARIHINI AI ICIN FORMATLIYORUZ
$todayTR = date('d.m.Y');

// SISTEM PROMPTU (GOLDER AI MASTER KILAVUZU - GUNCELLENDI)
$systemPrompt = "Sen Golder Kuyumcu Yonetim Programi'nin Bas Veri Analisti ve Yapay Zeka Asistanisin.
Bugunun Tarihi: {$todayTR}
Su an inceledigin subenin/profilin ID'si: {$activeProfileId}

GOREVIN: Kullanicinin dogal dilde sordugu sorulari 'execute_sql' aracini kullanarak MySQL veritabaninda sorgulamak ve cikan sonuclari kullaniciya anlasilir, kibar ve net bir dille sunmaktir.

ASAGIDAKI KURALLAR SENIN ANAYASANDIR. BIR SORGUNUN DOGRU CALISMASI ICIN BUNLARA KESINLIKLE UYMALISIN:

1. GUVENLIK VE KAPSAM:
- Yazdigin tum SELECT sorgularinda mutlaka `WHERE profile_id = '{$activeProfileId}'` sartini ekle.
- Tabloda `is_deleted` kolonu varsa mutlaka `COALESCE(is_deleted, 0) = 0` sartini ekle.

2. TARIH KAVRAMI (COK KRITIK):
- Veritabanindaki tarihler (transaction_date, event_date, sale_date, buy_date) MySQL DATE formatinda DEGIL, 'DD.MM.YYYY' (Orn: 25.10.2024) formatinda VARCHAR (metin) olarak tutulur.
- 'Bugun', 'Dun' gibi zaman sorgularinda ASLA CURDATE() KULLANMA. Daima LIKE kullan. (Orn: `event_date LIKE '%{$todayTR}%'`)

3. CARI BAKIYE HESAPLAMA (EN ONEMLI KURAL 1):
Sistemde cari bakiyeler 'debt_records' tablosunda DEGIL, musterinin 'customer_history_events' tablosundaki tum hareketlerinin toplanmasiyla bulunur!
SQL Ipucu: `SELECT event_type, debt_original, credit_original, currency, description, transaction_amount FROM customer_history_events WHERE person_full_name LIKE '%MusteriAdi%' AND profile_id = '{$activeProfileId}'`
Gelen sonucu kendi zihninde hesapla:
A) Normal Islemler: Musterinin Borcu = `debt_original`, Musterinin Alacagi = `credit_original`.
B) Karmasik/Bedelli Islemler (`description` '{' ile basliyorsa JSON'dur): JSON icindeki `exchange_items` dizisindeki `amount` ve `type` degerlerini topla.

4. NAKIT VE KART KASA BAKIYELERI (EN ONEMLI KURAL 2 - COZUM):
Kullanici 'kasalarimda ne kadar var', 'nakit bakiyem nedir', 'kasa durumum nedir' dediginde SAKIN `financial_accounts` tablosuna bakip 'bakiye yazmiyor' DEME!
Kasalarin bakiyesini bulmak icin O KASANIN GECMIS ISLEMLERINI TOPLAMALISIN.
Bunun icin KESINLIKLE SU SQL SORGUSUNU CALISTIR:
`SELECT fa.name as kasa_adi, fa.type as tur, ft.currency as birim, SUM(CASE WHEN ft.transaction_type = 'Income' THEN ft.amount ELSE -ft.amount END) as bakiye FROM financial_transactions ft JOIN financial_accounts fa ON ft.account_id = fa.id WHERE ft.profile_id = '{$activeProfileId}' AND COALESCE(ft.is_deleted, 0) = 0 GROUP BY fa.id, ft.currency HAVING bakiye <> 0`

5. ISIM ARAMALARI:
Kullanici 'Mervan' derse veritabaninda 'Mervan Kaya' olabilir. Daima LIKE kullan: `person_full_name LIKE '%Mervan%'`

6. CEVAP FORMATI:
- SQL kodunu kullaniciya GOSTERME.
- Sonuclari sik Markdown tablolari (HTML gorunumlu) ile liste yaparak ver.

Iste veritabani semasi:
" . $schemaDefinition;

if (empty($messages) || $messages[0]['role'] !== 'system') {
    array_unshift($messages, ["role" => "system", "content" => $systemPrompt]);
}

$apiKey = trim(golder_env('OPENAI_API_KEY', ''));
if ($apiKey === '') {
    golder_json_error(500, 'AI_CONFIG_ERROR', 'OpenAI API anahtari sunucuda tanimli degil.');
}

$model = trim(golder_env('OPENAI_MODEL', 'gpt-4o-mini'));
if ($model === '') {
    $model = 'gpt-4o-mini';
}

$data = [
    "model" => $model,
    "messages" => $messages,
    "temperature" => 0.2,
    "tools" => [
        [
            "type" => "function",
            "function" => [
                "name" => "execute_sql",
                "description" => "MySQL SELECT sorgusu calistirir.",
                "parameters" => [
                    "type" => "object",
                    "properties" => [
                        "query" => [
                            "type" => "string",
                            "description" => "Calistirilacak SELECT sorgusu."
                        ]
                    ],
                    "required" => ["query"]
                ]
            ]
        ]
    ]
];

if (!function_exists('curl_init')) {
    golder_json_error(500, 'AI_RUNTIME_ERROR', 'Sunucuda PHP cURL eklentisi etkin degil.');
}

$ch = curl_init("https://api.openai.com/v1/chat/completions");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 45);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer " . $apiKey
]);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
$curlErrno = curl_errno($ch);
curl_close($ch);

if ($response === false) {
    golder_json_error(
        500,
        'AI_TRANSPORT_ERROR',
        'OpenAI baglantisi kurulurken hata olustu.',
        ['details' => ['curl_errno' => $curlErrno, 'curl_error' => $curlError]]
    );
}

$result = json_decode($response, true);
if (!is_array($result)) {
    golder_json_error(500, 'AI_INVALID_RESPONSE', 'OpenAI gecersiz bir yanit dondurdu.');
}

if ($httpCode !== 200) {
    $openAiMessage = '';
    if (isset($result['error']['message']) && is_string($result['error']['message'])) {
        $openAiMessage = trim($result['error']['message']);
    } elseif (isset($result['message']) && is_string($result['message'])) {
        $openAiMessage = trim($result['message']);
    }

    golder_json_error(
        500,
        'AI_ERROR',
        $openAiMessage !== '' ? $openAiMessage : 'Yapay zeka servisi yanit vermedi.',
        ['details' => $result, 'openai_status' => $httpCode]
    );
}

$message = $result['choices'][0]['message'] ?? null;
if (!is_array($message)) {
    golder_json_error(500, 'AI_INVALID_RESPONSE', 'OpenAI yanitinda mesaj alani bulunamadi.', ['details' => $result]);
}

golder_json_response([
    'status' => 'ok',
    'message' => $message,
    'remaining_quota' => max(0, 100 - ($isNewQuestion ? $currentCount + 1 : $currentCount))
]);


