<?php
// chat_api.php - versi stabil: nama user benar, insert aman, outbound Telegram tetap jalan.
declare(strict_types=1);

ini_set('display_errors', '0');
ini_set('log_errors', '1');
error_reporting(E_ALL);

header('Content-Type: application/json; charset=utf-8');

require_once __DIR__ . '/config/database.php';
if (file_exists(__DIR__ . '/config/master_auth.php')) {
    require_once __DIR__ . '/config/master_auth.php';
}
if (file_exists(__DIR__ . '/config/telegram.php')) {
    require_once __DIR__ . '/config/telegram.php';
}

$conn = function_exists('getConnection') ? getConnection() : null;
if (!$conn instanceof mysqli) {
    echo json_encode(['ok' => false, 'error' => 'Koneksi database gagal']);
    exit;
}
$conn->set_charset('utf8mb4');

function chat_json(bool $ok, array $data = []): void {
    echo json_encode(array_merge(['ok' => $ok], $data), JSON_UNESCAPED_UNICODE);
    exit;
}

function chat_log(string $message): void {
    error_log('[CHAT_API_FIXED] ' . $message);
}

function chat_column_exists(mysqli $conn, string $table, string $column): bool {
    $safeTable = $conn->real_escape_string($table);
    $safeCol = $conn->real_escape_string($column);
    $res = $conn->query("SHOW COLUMNS FROM `{$safeTable}` LIKE '{$safeCol}'");
    return $res && $res->num_rows > 0;
}

function chat_ensure_schema(mysqli $conn): void {
    $conn->query("CREATE TABLE IF NOT EXISTS `group_chat_messages` (
        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
        `user_id` INT NULL,
        `employee_id` INT NULL,
        `user_name` VARCHAR(200) NOT NULL DEFAULT 'User',
        `user_role` VARCHAR(80) NOT NULL DEFAULT 'user',
        `message` TEXT NOT NULL,
        `source` VARCHAR(30) NOT NULL DEFAULT 'web',
        `status` VARCHAR(30) NOT NULL DEFAULT 'sent',
        `telegram_update_id` BIGINT NULL,
        `telegram_message_id` BIGINT NULL,
        `telegram_chat_id` VARCHAR(80) NULL,
        `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`),
        KEY `idx_created_at` (`created_at`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");

    $adds = [
        'user_id' => 'INT NULL',
        'employee_id' => 'INT NULL',
        'user_name' => "VARCHAR(200) NOT NULL DEFAULT 'User'",
        'user_role' => "VARCHAR(80) NOT NULL DEFAULT 'user'",
        'message' => 'TEXT NULL',
        'source' => "VARCHAR(30) NOT NULL DEFAULT 'web'",
        'status' => "VARCHAR(30) NOT NULL DEFAULT 'sent'",
        'telegram_update_id' => 'BIGINT NULL',
        'telegram_message_id' => 'BIGINT NULL',
        'telegram_chat_id' => 'VARCHAR(80) NULL',
        'created_at' => 'DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP',
    ];
    foreach ($adds as $col => $def) {
        if (!chat_column_exists($conn, 'group_chat_messages', $col)) {
            @$conn->query("ALTER TABLE `group_chat_messages` ADD COLUMN `{$col}` {$def}");
        }
    }

    $conn->query("CREATE TABLE IF NOT EXISTS `group_chat_telegram_logs` (
        `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
        `message_id` INT NULL,
        `direction` VARCHAR(20) NOT NULL DEFAULT 'outbound',
        `success` TINYINT(1) NOT NULL DEFAULT 0,
        `response_text` TEXT NULL,
        `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
}

function chat_current_user(mysqli $conn): array {
    if (session_status() !== PHP_SESSION_ACTIVE) {
        @session_start();
    }

    $master = null;
    if (function_exists('current_user')) {
        try { $master = current_user(); } catch (Throwable $e) { $master = null; }
    }

    $employeeId = 0;
    $userId = 0;
    $name = '';
    $role = '';

    if (is_array($master)) {
        $employeeId = (int)($master['employee_id'] ?? $master['id'] ?? 0);
        $userId = (int)($master['user_id'] ?? 0);
        $name = trim((string)($master['nama'] ?? $master['full_name'] ?? $master['name'] ?? ''));
        $role = trim((string)($master['role'] ?? ''));
    }

    $employeeId = $employeeId ?: (int)($_SESSION['employee_id'] ?? $_SESSION['user']['employee_id'] ?? 0);
    $userId = $userId ?: (int)($_SESSION['user_id'] ?? $_SESSION['user']['id'] ?? 0);
    $name = $name ?: trim((string)($_SESSION['full_name'] ?? $_SESSION['user']['full_name'] ?? $_SESSION['user']['name'] ?? $_SESSION['username'] ?? ''));
    $role = $role ?: trim((string)($_SESSION['user_role'] ?? $_SESSION['user']['role'] ?? 'user'));

    if ($employeeId > 0) {
        $stmt = $conn->prepare("SELECT full_name FROM employees WHERE id = ? LIMIT 1");
        if ($stmt) {
            $stmt->bind_param('i', $employeeId);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($row = $res->fetch_assoc()) {
                if (!empty($row['full_name'])) $name = $row['full_name'];
            }
            $stmt->close();
        }
    }

    if (($name === '' || strtolower($name) === 'user') && $userId > 0) {
        $stmt = $conn->prepare("SELECT u.username, u.role, e.id AS employee_id, e.full_name
            FROM users u
            LEFT JOIN employees e ON e.id = u.employee_id
            WHERE u.id = ? LIMIT 1");
        if ($stmt) {
            $stmt->bind_param('i', $userId);
            $stmt->execute();
            $res = $stmt->get_result();
            if ($row = $res->fetch_assoc()) {
                $employeeId = $employeeId ?: (int)($row['employee_id'] ?? 0);
                $name = trim((string)($row['full_name'] ?: $row['username'] ?: $name));
                $role = trim((string)($row['role'] ?: $role));
            }
            $stmt->close();
        }
    }

    if ($name === '') $name = 'User';
    if ($role === '') $role = 'user';

    return [
        'user_id' => $userId ?: null,
        'employee_id' => $employeeId ?: null,
        'user_name' => $name,
        'user_role' => $role,
    ];
}

function chat_send_telegram(string $userName, string $role, string $message, ?int $messageId = null): bool {
    if (!defined('TELEGRAM_BOT_TOKEN') || !defined('TELEGRAM_CHAT_ID_KEPERAWATAN')) return false;
    $token = trim((string)TELEGRAM_BOT_TOKEN);
    $chatId = trim((string)TELEGRAM_CHAT_ID_KEPERAWATAN);
    if ($token === '' || $chatId === '') return false;

    // Hindari kirim ulang pesan inbound Telegram ke Telegram.
    $text = "💬 CHAT GRUP KEPERAWATAN\n" .
            "👤 {$userName} ({$role})\n" .
            "🕒 " . date('d-m-Y H:i') . "\n\n" .
            $message;

    $url = "https://api.telegram.org/bot{$token}/sendMessage";
    $payload = [
        'chat_id' => $chatId,
        'text' => $text,
        'parse_mode' => 'HTML',
        'disable_web_page_preview' => true,
    ];

    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => $payload,
        CURLOPT_TIMEOUT => 8,
    ]);
    $response = curl_exec($ch);
    $err = curl_error($ch);
    $http = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $ok = ($response !== false && $http >= 200 && $http < 300);
    if (!$ok) chat_log('Telegram send gagal: HTTP ' . $http . ' ' . $err . ' ' . (string)$response);
    return $ok;
}

try {
    chat_ensure_schema($conn);

    $action = $_POST['action'] ?? $_GET['action'] ?? 'list';
    if ($action === 'fetch' || $action === 'load') $action = 'list';

    if ($action === 'list') {
        $limit = (int)($_GET['limit'] ?? 100);
        if ($limit < 1) $limit = 100;
        if ($limit > 300) $limit = 300;

        $sql = "SELECT id, user_id, employee_id,
                       COALESCE(NULLIF(user_name,''), 'User') AS user_name,
                       COALESCE(NULLIF(user_role,''), 'user') AS user_role,
                       COALESCE(message,'') AS message,
                       COALESCE(source,'web') AS source,
                       created_at
                FROM group_chat_messages
                WHERE message IS NOT NULL AND message <> ''
                ORDER BY id DESC
                LIMIT ?";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('i', $limit);
        $stmt->execute();
        $res = $stmt->get_result();
        $rows = [];
        while ($r = $res->fetch_assoc()) {
            $rows[] = $r;
        }
        $stmt->close();
        $rows = array_reverse($rows);
        chat_json(true, ['messages' => $rows]);
    }

    if ($action === 'send') {
        $message = trim((string)($_POST['message'] ?? $_POST['text'] ?? ''));
        if ($message === '') chat_json(false, ['error' => 'Pesan kosong']);
        if (mb_strlen($message) > 4000) $message = mb_substr($message, 0, 4000);

        $cu = chat_current_user($conn);
        $source = 'web';
        $status = 'sent';
        $userId = $cu['user_id'];
        $employeeId = $cu['employee_id'];
        $userName = $cu['user_name'];
        $userRole = $cu['user_role'];

        $stmt = $conn->prepare("INSERT INTO group_chat_messages
            (user_id, employee_id, user_name, user_role, message, source, status, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, NOW())");
        if (!$stmt) throw new Exception('Prepare insert gagal: ' . $conn->error);
        $stmt->bind_param('iisssss', $userId, $employeeId, $userName, $userRole, $message, $source, $status);
        $stmt->execute();
        $messageId = (int)$conn->insert_id;
        $stmt->close();

        $telegramOk = chat_send_telegram($userName, $userRole, $message, $messageId);
        $resp = $telegramOk ? 'OK' : 'FAILED_OR_DISABLED';
        $dir = 'outbound';
        $success = $telegramOk ? 1 : 0;
        $stmtLog = $conn->prepare("INSERT INTO group_chat_telegram_logs (message_id, direction, success, response_text, created_at) VALUES (?, ?, ?, ?, NOW())");
        if ($stmtLog) {
            $stmtLog->bind_param('isis', $messageId, $dir, $success, $resp);
            $stmtLog->execute();
            $stmtLog->close();
        }

        chat_json(true, ['id' => $messageId, 'telegram_sent' => $telegramOk, 'user_name' => $userName]);
    }

    if ($action === 'unread') {
        chat_json(true, ['unread' => 0]);
    }

    if ($action === 'mark_read') {
        chat_json(true, ['marked' => true]);
    }

    chat_json(false, ['error' => 'Action tidak dikenal: ' . $action]);
} catch (Throwable $e) {
    chat_log($e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine());
    chat_json(false, ['error' => $e->getMessage()]);
}
