<?php
// Get Buku Mimpi Data for AJAX
// File: get-buku-mimpi-data.php

session_start();

// Check integrated admin authentication (same as master admin)
if (!isset($_SESSION['integrated_admin_session_id'])) {
    http_response_code(401);
    echo json_encode([
        'success' => false, 
        'message' => 'Unauthorized - Please login first',
        'debug' => [
            'session_integrated_admin_session_id' => isset($_SESSION['integrated_admin_session_id']),
            'session_id' => session_id()
        ]
    ]);
    exit;
}

// Additional auth validation using IntegratedAdminAuth
require_once '../includes/integrated-admin-auth.php';
$integratedAuth = new IntegratedAdminAuth();
$adminData = $integratedAuth->validateSession($_SESSION['integrated_admin_session_id']);
if (!$adminData) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'Invalid session']);
    exit;
}

// Gunakan koneksi DB pusat via kelas Database (jangan override konstanta DB_ lokal)
// require_once Database hanya di-root; ini memastikan kita pakai konfigurasi pusat

header('Content-Type: application/json');

if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['site'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

$site_code = $_POST['site'];
$allowed_sites = ['mayortogel', 'wajahtoto', 'yuki585'];

if (!in_array($site_code, $allowed_sites)) {
    echo json_encode(['success' => false, 'message' => 'Invalid site']);
    exit;
}

try {
    // Pakai kelas Database terpusat untuk mendapatkan PDO connection
    require_once __DIR__ . '/../includes/database.php';
    $db = new Database();
    $pdo = $db->getConnection();

    // Nama tabel spesifik site
    $tableName = 'buku_mimpi_' . $site_code;

    // Check if table exists first
    $checkStmt = $pdo->prepare("SHOW TABLES LIKE ?");
    $checkStmt->execute([$tableName]);
    
    if ($checkStmt->rowCount() == 0) {
        echo json_encode([
            'success' => false,
            'message' => "Tabel {$tableName} tidak ditemukan"
        ]);
        exit;
    }

    $sql = "SELECT id, title, angka_2d, description, category, image_url, is_active, created_at, updated_at FROM {$tableName} ORDER BY angka_2d";
    $stmt = $pdo->prepare($sql);
    $stmt->execute();
    $items = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    echo json_encode([
        'success' => true,
        'items' => $items,
        'count' => count($items),
        'site' => $site_code
    ]);
    
} catch (PDOException $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database connection error: ' . $e->getMessage(),
        'site' => $site_code
    ]);
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Error: ' . $e->getMessage(),
        'site' => $site_code
    ]);
}
?>