<?php
// api/chat.php — Chat antara masyarakat dan rumah ibadah
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { http_response_code(200); exit; }

require_once '../includes/config.php';
startSession();
requireLogin(['masyarakat','pengurus_ibadah','admin']);

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? 'conversations';
$role   = $_SESSION['role'] ?? '';
$uid    = (int)$_SESSION['user_id'];
$myIbadah = (int)($_SESSION['id_rumah_ibadah'] ?? 0);

// ── GET: daftar percakapan ──────────────────────────────────
if ($method === 'GET' && $action === 'conversations') {
    if ($role === 'masyarakat') {
        // Percakapan masyarakat (grouped by rumah ibadah)
        $res = $conn->query("
            SELECT c.id_rumah_ibadah,
                   ri.nama AS nama_ibadah, ri.jenis AS jenis_ibadah,
                   MAX(c.created_at) AS last_time,
                   COUNT(*) AS total_pesan,
                   SUM(c.is_read=0 AND c.pengirim_role='pengurus_ibadah') AS unread
            FROM chat_masyarakat c
            JOIN rumah_ibadah ri ON c.id_rumah_ibadah=ri.id
            WHERE c.id_user_masyarakat=$uid
            GROUP BY c.id_rumah_ibadah
            ORDER BY last_time DESC
        ");
    } else {
        // Percakapan pengurus (grouped by masyarakat user)
        $res = $conn->query("
            SELECT c.id_user_masyarakat,
                   u.nama_lengkap AS nama_masyarakat,
                   MAX(c.created_at) AS last_time,
                   COUNT(*) AS total_pesan,
                   SUM(c.is_read=0 AND c.pengirim_role='masyarakat') AS unread
            FROM chat_masyarakat c
            JOIN users u ON c.id_user_masyarakat=u.id
            WHERE c.id_rumah_ibadah=$myIbadah
            GROUP BY c.id_user_masyarakat
            ORDER BY last_time DESC
        ");
    }
    $data = [];
    while ($r = $res->fetch_assoc()) $data[] = $r;
    jsonResponse($data);
}

// ── GET: pesan dalam percakapan ────────────────────────────
if ($method === 'GET' && $action === 'messages') {
    if ($role === 'masyarakat') {
        $id_ibadah = (int)($_GET['id_rumah_ibadah'] ?? 0);
        if (!$id_ibadah) jsonResponse(['error'=>'id_rumah_ibadah diperlukan'], 400);

        // Tandai pesan dari pengurus sebagai dibaca
        $conn->query("UPDATE chat_masyarakat SET is_read=1
                      WHERE id_user_masyarakat=$uid AND id_rumah_ibadah=$id_ibadah
                      AND pengirim_role='pengurus_ibadah' AND is_read=0");

        $res = $conn->query("
            SELECT c.*, ri.nama AS nama_ibadah, u.nama_lengkap AS nama_pengirim
            FROM chat_masyarakat c
            JOIN rumah_ibadah ri ON c.id_rumah_ibadah=ri.id
            JOIN users u ON c.id_pengirim=u.id
            WHERE c.id_user_masyarakat=$uid AND c.id_rumah_ibadah=$id_ibadah
            ORDER BY c.created_at ASC LIMIT 200
        ");
    } else {
        // Pengurus: lihat chat dengan masyarakat tertentu
        $id_user = (int)($_GET['id_user_masyarakat'] ?? 0);
        if (!$id_user) jsonResponse(['error'=>'id_user_masyarakat diperlukan'], 400);

        // Tandai pesan dari masyarakat sebagai dibaca
        $conn->query("UPDATE chat_masyarakat SET is_read=1
                      WHERE id_user_masyarakat=$id_user AND id_rumah_ibadah=$myIbadah
                      AND pengirim_role='masyarakat' AND is_read=0");

        $res = $conn->query("
            SELECT c.*, ri.nama AS nama_ibadah, u.nama_lengkap AS nama_pengirim
            FROM chat_masyarakat c
            JOIN rumah_ibadah ri ON c.id_rumah_ibadah=ri.id
            JOIN users u ON c.id_pengirim=u.id
            WHERE c.id_user_masyarakat=$id_user AND c.id_rumah_ibadah=$myIbadah
            ORDER BY c.created_at ASC LIMIT 200
        ");
    }
    $data = [];
    while ($r = $res->fetch_assoc()) $data[] = $r;
    jsonResponse($data);
}

// ── GET: daftar rumah ibadah (untuk masyarakat memilih tujuan) ──
if ($method === 'GET' && $action === 'ibadah_list') {
    $res = $conn->query("SELECT id, nama, jenis, kecamatan FROM rumah_ibadah ORDER BY nama");
    $data = [];
    while ($r = $res->fetch_assoc()) $data[] = $r;
    jsonResponse($data);
}

// ── GET: hitung unread ──────────────────────────────────────
if ($method === 'GET' && $action === 'unread') {
    if ($role === 'masyarakat') {
        $r = $conn->query("SELECT COUNT(*) AS n FROM chat_masyarakat
                           WHERE id_user_masyarakat=$uid AND pengirim_role='pengurus_ibadah' AND is_read=0")
                   ->fetch_assoc();
    } else {
        $r = $conn->query("SELECT COUNT(*) AS n FROM chat_masyarakat
                           WHERE id_rumah_ibadah=$myIbadah AND pengirim_role='masyarakat' AND is_read=0")
                   ->fetch_assoc();
    }
    jsonResponse(['unread' => (int)($r['n'] ?? 0)]);
}

// ── POST: kirim pesan ──────────────────────────────────────
if ($method === 'POST') {
    $d = json_decode(file_get_contents('php://input'), true);
    $isi = trim(esc($conn, $d['isi'] ?? ''));
    if (!$isi) jsonResponse(['success'=>false,'error'=>'Pesan tidak boleh kosong'], 400);

    if ($role === 'masyarakat') {
        $id_ibadah = (int)($d['id_rumah_ibadah'] ?? 0);
        if (!$id_ibadah) jsonResponse(['success'=>false,'error'=>'Rumah ibadah tidak dipilih'], 400);

        $sql = "INSERT INTO chat_masyarakat
                (id_user_masyarakat, id_rumah_ibadah, id_pengirim, pengirim_role, isi_pesan)
                VALUES ($uid, $id_ibadah, $uid, 'masyarakat', '$isi')";
        if ($conn->query($sql)) {
            $cid = $conn->insert_id;
            // Notif ke pengurus rumah ibadah
            $peng = $conn->query("SELECT id FROM users WHERE id_rumah_ibadah=$id_ibadah AND role='pengurus_ibadah'");
            while ($p = $peng->fetch_assoc()) {
                kirimNotifikasi($conn, (int)$p['id'], 'Pesan Chat Baru', 'Ada pesan baru dari masyarakat.', 'chat_baru', $cid);
            }
            jsonResponse(['success'=>true, 'id'=>$cid]);
        } else {
            jsonResponse(['success'=>false,'error'=>$conn->error], 500);
        }
    } else {
        // Pengurus membalas ke masyarakat
        $id_user_mas = (int)($d['id_user_masyarakat'] ?? 0);
        if (!$id_user_mas || !$myIbadah) jsonResponse(['success'=>false,'error'=>'Data tidak lengkap'], 400);

        $sql = "INSERT INTO chat_masyarakat
                (id_user_masyarakat, id_rumah_ibadah, id_pengirim, pengirim_role, isi_pesan)
                VALUES ($id_user_mas, $myIbadah, $uid, 'pengurus_ibadah', '$isi')";
        if ($conn->query($sql)) {
            $cid = $conn->insert_id;
            // Notif ke masyarakat
            kirimNotifikasi($conn, $id_user_mas, 'Pesan dari Rumah Ibadah', 'Rumah ibadah mengirim pesan baru.', 'chat_baru', $cid);
            jsonResponse(['success'=>true, 'id'=>$cid]);
        } else {
            jsonResponse(['success'=>false,'error'=>$conn->error], 500);
        }
    }
}
?>
