<?php
include 'config.php';
header('Content-Type: application/json');

$action = $_GET['action'] ?? '';

// 1. SUMMARY (Untuk Dashboard Stats)
if ($action === 'summary') {
    $total_pasien = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as count FROM pendaftaran"))['count'];
    $total_dokter = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as count FROM dokter"))['count'];
    $total_berita = mysqli_fetch_assoc(mysqli_query($conn, "SELECT COUNT(*) as count FROM berita"))['count'];
    
    // Stats mingguan sederhana
    $weekly = [5, 8, 12, 7, 10, 15, 9];
    $ratings = [2, 5, 15, 45]; // Rating 1, 2, 3, 4
    
    echo json_encode([
        'total_pasien' => $total_pasien,
        'total_dokter' => $total_dokter,
        'total_berita' => $total_berita,
        'weekly_stats' => $weekly,
        'rating_stats' => $ratings
    ]);
    exit;
}

// 2. FETCH DATA
if ($action === 'fetch') {
    $table = $_GET['table'] ?? '';
    if ($table === 'settings') {
        $sql = "SELECT * FROM `$table` WHERE id = 1 LIMIT 1";
    } else {
        $sql = "SELECT * FROM `$table` ORDER BY id DESC";
    }
    $result = mysqli_query($conn, $sql);
    $data = [];
    while ($row = mysqli_fetch_assoc($result)) { $data[] = $row; }
    echo json_encode($data);
    exit;
}

// 3. DELETE DATA
if ($action === 'delete') {
    $table = $_GET['table'] ?? '';
    $id = $_GET['id'] ?? 0;
    mysqli_query($conn, "DELETE FROM `$table` WHERE id = $id");
    echo json_encode(['status' => 'success']);
    exit;
}

// 4. ADD / EDIT DATA (PUSAT LOGIKA)
if ($action === 'add') {
    $table = $_GET['table'] ?? '';
    $id = $_POST['id'] ?? null;
    $fields = [];

    // --- KHUSUS DOKTER: Gabung Poli, Hari, & Jam ---
    if ($table === 'dokter') {
        $poli = $_POST['poli_nama'] ?? '';
        $hari = $_POST['jadwal_hari'] ?? '';
        $jam = $_POST['jadwal_jam'] ?? '';
        $_POST['spesialis'] = "$poli<br>$hari | $jam";
        unset($_POST['poli_nama'], $_POST['jadwal_hari'], $_POST['jadwal_jam']);
    }

    // --- LOGIKA UPLOAD ---
    $file_field = '';
    if ($table === 'dokter') $file_field = 'foto';
    if ($table === 'berita') $file_field = 'gambar';
    if ($table === 'settings') $file_field = 'logo'; // Kita tangani khusus settings di bawah

    if ($file_field && isset($_FILES[$file_field]) && $_FILES[$file_field]['error'] === 0) {
        $ext = pathinfo($_FILES[$file_field]['name'], PATHINFO_EXTENSION);
        $filename = $table . '_' . time() . '.' . $ext;
        move_uploaded_file($_FILES[$file_field]['tmp_name'], "../uploads/" . $filename);
        $_POST[$file_field] = $filename;
        unset($_POST["old_$file_field"]);
    } else if (isset($_POST["old_$file_field"])) {
        $_POST[$file_field] = $_POST["old_$file_field"];
        unset($_POST["old_$file_field"]);
    }

    // --- KHUSUS SETTINGS: Background Upload ---
    if ($table === 'settings' && isset($_FILES['background']) && $_FILES['background']['error'] === 0) {
        $ext = pathinfo($_FILES['background']['name'], PATHINFO_EXTENSION);
        $bg_filename = 'bg_' . time() . '.' . $ext;
        move_uploaded_file($_FILES['background']['tmp_name'], "../uploads/" . $bg_filename);
        $_POST['background'] = $bg_filename;
    }

    // --- BANGUN QUERY ---
    $updates = [];
    foreach ($_POST as $key => $val) {
        if ($key !== 'id') {
            $value = mysqli_real_escape_string($conn, $val);
            $updates[] = "`$key` = '$value'";
        }
    }

    if ($table === 'settings') {
        $sql = "UPDATE settings SET " . implode(", ", $updates) . " WHERE id = 1";
    } elseif ($id) {
        $sql = "UPDATE `$table` SET " . implode(", ", $updates) . " WHERE id = $id";
    } else {
        $cols = []; $vals = [];
        foreach ($_POST as $key => $val) {
            if ($key !== 'id') {
                $cols[] = "`$key`";
                $vals[] = "'" . mysqli_real_escape_string($conn, $val) . "'";
            }
        }
        $sql = "INSERT INTO `$table` (" . implode(",", $cols) . ") VALUES (" . implode(",", $vals) . ")";
    }

    if (mysqli_query($conn, $sql)) {
        echo json_encode(['status' => 'success']);
    } else {
        echo json_encode(['status' => 'error', 'message' => mysqli_error($conn)]);
    }
    exit;
}

echo json_encode(['status' => 'error', 'message' => 'Action not found']);
?>
