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

require_once '../includes/config.php';
requireLogin(['admin','pengurus_ibadah']);
startSession();
$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? 'inbox';

$myIbadah = (int)($_SESSION['id_rumah_ibadah']??0);
$uid      = (int)$_SESSION['user_id'];

// ── GET: inbox ─────────────────────────────────────────────
if ($method === 'GET' && $action === 'inbox') {
    $res = $conn->query("SELECT pai.*,
        ri_k.nama AS dari_ibadah, ri_k.jenis AS jenis_dari,
        ri_t.nama AS kepada_ibadah,
        p.nama_kepala_keluarga, p.alamat AS alamat_kk,
        u.nama_lengkap AS nama_pengirim
        FROM pesan_antar_ibadah pai
        JOIN rumah_ibadah ri_k  ON pai.id_pengirim_ibadah=ri_k.id
        JOIN rumah_ibadah ri_t  ON pai.id_penerima_ibadah=ri_t.id
        LEFT JOIN penduduk p    ON pai.id_penduduk=p.id
        LEFT JOIN users u       ON pai.id_pengirim_user=u.id
        WHERE pai.id_penerima_ibadah=$myIbadah
        ORDER BY pai.created_at DESC LIMIT 100");
    $data = [];
    while ($r = $res->fetch_assoc()) $data[] = $r;
    jsonResponse($data);
}

// ── GET: outbox ────────────────────────────────────────────
if ($method === 'GET' && $action === 'outbox') {
    $res = $conn->query("SELECT pai.*,
        ri_t.nama AS kepada_ibadah,
        p.nama_kepala_keluarga,
        u.nama_lengkap AS nama_pengirim
        FROM pesan_antar_ibadah pai
        JOIN rumah_ibadah ri_t  ON pai.id_penerima_ibadah=ri_t.id
        LEFT JOIN penduduk p    ON pai.id_penduduk=p.id
        LEFT JOIN users u       ON pai.id_pengirim_user=u.id
        WHERE pai.id_pengirim_ibadah=$myIbadah
        ORDER BY pai.created_at DESC LIMIT 100");
    $data = [];
    while ($r = $res->fetch_assoc()) $data[] = $r;
    jsonResponse($data);
}

// ── POST: kirim pesan ──────────────────────────────────────
if ($method === 'POST') {
    $d           = json_decode(file_get_contents('php://input'), true);
    $to_ibadah   = (int)($d['id_penerima_ibadah']??0);
    $id_penduduk = (int)($d['id_penduduk']??0) ?: 'NULL';
    $perihal     = esc($conn,$d['perihal']??'');
    $isi         = esc($conn,$d['isi_pesan']??'');

    if (!$to_ibadah||!$perihal||!$isi)
        jsonResponse(['success'=>false,'error'=>'Data tidak lengkap'],400);

    $sql = "INSERT INTO pesan_antar_ibadah
            (id_pengirim_ibadah,id_penerima_ibadah,id_penduduk,id_pengirim_user,perihal,isi_pesan)
            VALUES ($myIbadah,$to_ibadah,$id_penduduk,$uid,'$perihal','$isi')";
    if ($conn->query($sql)) {
        $pid2 = $conn->insert_id;
        // Notif ke pengurus penerima
        $peng = $conn->query("SELECT id FROM users WHERE id_rumah_ibadah=$to_ibadah AND role='pengurus_ibadah'");
        while ($p = $peng->fetch_assoc()) {
            kirimNotifikasi($conn,(int)$p['id'],"Pesan Baru dari Rumah Ibadah","$perihal",'pesan_baru',$pid2);
        }
        logAktivitas($conn,'kirim_pesan','pesan_antar_ibadah',$pid2,"Ke ibadah ID:$to_ibadah");
        jsonResponse(['success'=>true,'id'=>$pid2,'message'=>'Pesan berhasil dikirim']);
    } else {
        jsonResponse(['success'=>false,'error'=>$conn->error],500);
    }
}

// ── PUT: balas / update status ─────────────────────────────
if ($method === 'PUT') {
    $d      = json_decode(file_get_contents('php://input'), true);
    $id     = (int)$d['id'];
    $status = esc($conn,$d['status_pesan']??'dibaca');
    $balas  = esc($conn,$d['pesan_balasan']??'');

    $sql = "UPDATE pesan_antar_ibadah SET status_pesan='$status',
            pesan_balasan='$balas',id_penerima_user=$uid,dibalas_at=NOW()
            WHERE id=$id AND id_penerima_ibadah=$myIbadah";
    if ($conn->query($sql)) {
        // Notif ke pengirim asal
        $pesan = $conn->query("SELECT id_pengirim_user FROM pesan_antar_ibadah WHERE id=$id")->fetch_assoc();
        if ($pesan && $pesan['id_pengirim_user']) {
            kirimNotifikasi($conn,(int)$pesan['id_pengirim_user'],
                'Pesan Dibalas','Permintaan bantuan Anda telah direspons.','pesan_baru',$id);
        }
        jsonResponse(['success'=>true,'message'=>'Pesan diperbarui']);
    } else {
        jsonResponse(['success'=>false,'error'=>$conn->error],500);
    }
}
?>

<?php
// Tambahkan file api/notifikasi.php inline
?>
