<?php
// ============================================================
// FILE: chat_api.php — API endpoint chat (long-polling)
// Dipanggil via fetch() dari chat.php dan admin/chat.php
//
// GET  ?action=poll&pesanan_id=X&last_id=Y  → ambil pesan baru
// POST action=kirim                         → kirim pesan
// GET  ?action=unread                       → jumlah belum dibaca (admin)
// ============================================================
require_once __DIR__ . '/includes/config.php';
require_once __DIR__ . '/includes/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/auth.php';

header('Content-Type: application/json');
header('Cache-Control: no-cache, no-store');

$pdo    = db();
$action = $_GET['action'] ?? $_POST['action'] ?? '';

// ── Helper: verifikasi akses pesanan ─────────────────────────
function getPesanan(PDO $pdo, int $pesananId, string $kode = ''): array|false {
    if ($pesananId) {
        $s = $pdo->prepare("SELECT id, kode_pesanan, nama_pembeli, status FROM pesanan WHERE id=? LIMIT 1");
        $s->execute([$pesananId]);
    } else {
        $s = $pdo->prepare("SELECT id, kode_pesanan, nama_pembeli, status FROM pesanan WHERE kode_pesanan=? LIMIT 1");
        $s->execute([$kode]);
    }
    return $s->fetch() ?: false;
}

// ── Tandai pesan sebagai dibaca ───────────────────────────────
function tandaiDibaca(PDO $pdo, int $pesananId, string $pengirimLawan): void {
    $pdo->prepare("UPDATE chat_pesan SET dibaca=1 WHERE pesanan_id=? AND pengirim=? AND dibaca=0")
        ->execute([$pesananId, $pengirimLawan]);
}

// ══════════════════════════════════════════════════════════════
// POLL — ambil pesan baru (long-polling)
// ══════════════════════════════════════════════════════════════
if ($action === 'poll') {
    $pesananId = (int)($_GET['pesanan_id'] ?? 0);
    $lastId    = (int)($_GET['last_id']   ?? 0);
    $kode      = trim($_GET['kode'] ?? '');
    $isAdmin   = isAdmin();

    // Verifikasi akses
    $pesanan = getPesanan($pdo, $pesananId, $kode);
    if (!$pesanan) { echo json_encode(['ok'=>false,'error'=>'Pesanan tidak ditemukan']); exit; }

    // Tandai dibaca
    tandaiDibaca($pdo, $pesanan['id'], $isAdmin ? 'pelanggan' : 'admin');

    // Long polling — tunggu max 25 detik jika belum ada pesan baru
    $timeout = 25;
    $start   = time();
    $pesan   = [];

    while (empty($pesan) && (time() - $start) < $timeout) {
        $s = $pdo->prepare("
            SELECT id, pengirim, pesan, dibaca,
                   DATE_FORMAT(created_at, '%H:%i') AS jam,
                   DATE_FORMAT(created_at, '%d %b %Y') AS tgl,
                   created_at
            FROM chat_pesan
            WHERE pesanan_id=? AND id > ?
            ORDER BY id ASC LIMIT 50
        ");
        $s->execute([$pesanan['id'], $lastId]);
        $pesan = $s->fetchAll();
        if (empty($pesan)) usleep(800000); // tunggu 0.8 detik
    }

    echo json_encode([
        'ok'      => true,
        'pesan'   => $pesan,
        'pesanan' => $pesanan,
    ]);
    exit;
}

// ══════════════════════════════════════════════════════════════
// KIRIM pesan
// ══════════════════════════════════════════════════════════════
if ($action === 'kirim' && $_SERVER['REQUEST_METHOD'] === 'POST') {
    $pesananId = (int)($_POST['pesanan_id'] ?? 0);
    $kode      = trim($_POST['kode'] ?? '');
    $teks      = trim($_POST['pesan'] ?? '');
    $isAdmin   = isAdmin();

    if (!$teks || mb_strlen($teks) > 2000) {
        echo json_encode(['ok'=>false,'error'=>'Pesan kosong atau terlalu panjang']); exit;
    }

    $pesanan = getPesanan($pdo, $pesananId, $kode);
    if (!$pesanan) { echo json_encode(['ok'=>false,'error'=>'Pesanan tidak ditemukan']); exit;  }

    // Pelanggan harus tahu kode pesanan (verifikasi minimal)
    if (!$isAdmin && $kode !== $pesanan['kode_pesanan']) {
        echo json_encode(['ok'=>false,'error'=>'Akses ditolak']); exit;
    }

    $pengirim = $isAdmin ? 'admin' : 'pelanggan';
    $s = $pdo->prepare("INSERT INTO chat_pesan (pesanan_id, pengirim, pesan) VALUES (?,?,?)");
    $s->execute([$pesanan['id'], $pengirim, $teks]);
    $newId = (int)$pdo->lastInsertId();

    $baru = $pdo->prepare("
        SELECT id, pengirim, pesan, dibaca,
               DATE_FORMAT(created_at,'%H:%i') AS jam,
               DATE_FORMAT(created_at,'%d %b %Y') AS tgl
        FROM chat_pesan WHERE id=?
    ");
    $baru->execute([$newId]);

    echo json_encode(['ok'=>true, 'pesan'=>$baru->fetch()]);
    exit;
}

// ══════════════════════════════════════════════════════════════
// UNREAD — jumlah pesan belum dibaca untuk admin
// ══════════════════════════════════════════════════════════════
if ($action === 'unread') {
    if (!isAdmin()) { echo json_encode(['ok'=>false,'total'=>0]); exit; }
    $total = $pdo->query("
        SELECT COUNT(*) FROM chat_pesan WHERE pengirim='pelanggan' AND dibaca=0
    ")->fetchColumn();
    // Per pesanan
    $perPesanan = $pdo->query("
        SELECT p.kode_pesanan, p.nama_pembeli, COUNT(c.id) AS jml
        FROM chat_pesan c
        JOIN pesanan p ON p.id = c.pesanan_id
        WHERE c.pengirim='pelanggan' AND c.dibaca=0
        GROUP BY c.pesanan_id
        ORDER BY MAX(c.created_at) DESC
        LIMIT 10
    ")->fetchAll();
    echo json_encode(['ok'=>true,'total'=>(int)$total,'per_pesanan'=>$perPesanan]);
    exit;
}

// ══════════════════════════════════════════════════════════════
// RIWAYAT — ambil semua pesan (tanpa polling)
// ══════════════════════════════════════════════════════════════
if ($action === 'riwayat') {
    $pesananId = (int)($_GET['pesanan_id'] ?? 0);
    $kode      = trim($_GET['kode'] ?? '');
    $isAdmin   = isAdmin();

    $pesanan = getPesanan($pdo, $pesananId, $kode);
    if (!$pesanan) { echo json_encode(['ok'=>false,'error'=>'Tidak ditemukan']); exit; }

    tandaiDibaca($pdo, $pesanan['id'], $isAdmin ? 'pelanggan' : 'admin');

    $s = $pdo->prepare("
        SELECT id, pengirim, pesan, dibaca,
               DATE_FORMAT(created_at,'%H:%i') AS jam,
               DATE_FORMAT(created_at,'%d %b %Y') AS tgl
        FROM chat_pesan WHERE pesanan_id=?
        ORDER BY id ASC LIMIT 200
    ");
    $s->execute([$pesanan['id']]);
    echo json_encode(['ok'=>true,'pesan'=>$s->fetchAll(),'pesanan'=>$pesanan]);
    exit;
}

echo json_encode(['ok'=>false,'error'=>'Action tidak dikenal']);