<?php
session_start();

// Proteksi: Hanya Admin yang bisa download
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    die("Akses Ditolak. Anda bukan Admin.");
}

$host = 'localhost';
$user = 'majapahi_omnich';
$pass = 'A1b2c3d4.,@';
$db   = 'majapahi_omnich';
$conn = new mysqli($host, $user, $pass, $db);

// Mengatur Header agar browser mendownloadnya sebagai file Excel (CSV)
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="Laporan_OmniWA_' . date('Y-m-d') . '.csv"');

// Membuat output stream
$output = fopen('php://output', 'w');

// Menulis Baris Judul Kolom di Excel
fputcsv($output, array('No', 'Nomor WA', 'Nama Pelanggan', 'Status Tiket', 'Kategori (Label)', 'Dilayani Oleh', 'Total Pesan (Masuk & Keluar)', 'Tanggal Terakhir Aktif', 'Catatan CS'));

// Mengambil data dari database
$query = "SELECT c.*, 
          (SELECT COUNT(*) FROM messages m WHERE m.phone_number = c.phone_number) as total_chat,
          (SELECT MAX(created_at) FROM messages m WHERE m.phone_number = c.phone_number) as last_active
          FROM contacts c ORDER BY last_active DESC";
          
$result = $conn->query($query);

// Looping data dan memasukkannya ke baris Excel
$no = 1;
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        fputcsv($output, array(
            $no++,
            "'" . $row['phone_number'], // Tanda kutip agar angka 0/kode negara tidak hilang di Excel
            $row['name'],
            strtoupper($row['status']),
            empty($row['label']) ? 'Belum Dilabeli' : $row['label'],
            empty($row['assigned_to']) ? 'Bot/Belum Diambil' : $row['assigned_to'],
            $row['total_chat'],
            $row['last_active'],
            $row['notes']
        ));
    }
}
fclose($output);
exit;
?>