<?php
// Konfigurasi Database
// $host = 'localhost';
// $user = 'root';
// $pass = '';
// $db   = 'pos_m';

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

// Koneksi ke database
try {
    include_once '../data.php';
    $conn = new mysqli($servername, $username, $password, $dbname);
    // $conn = new mysqli($host, $user, $pass, $db);
    if ($conn->connect_error) {
        throw new Exception("Koneksi gagal: " . $conn->connect_error);
    }
    $conn->set_charset("utf8");
    
    // Buat tabel pivot_reports jika belum ada
    $createTableQuery = "
    CREATE TABLE IF NOT EXISTS pivot_reports (
        id INT AUTO_INCREMENT PRIMARY KEY,
        report_name VARCHAR(255) NOT NULL,
        report_data TEXT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        UNIQUE KEY (report_name)
    )";
    
    $conn->query($createTableQuery);
    
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
    exit();
}

// Ambil aksi dari request (bisa dari GET atau POST)
$action = $_REQUEST['action'] ?? '';

switch ($action) {
    // Aksi untuk mengambil semua nama laporan
    case 'fetch':
        $result = $conn->query("SELECT report_name FROM pivot_reports ORDER BY report_name ASC");
        $reports = [];
        while ($row = $result->fetch_assoc()) {
            $reports[] = $row['report_name'];
        }
        echo json_encode($reports);
        break;
        
    // Aksi untuk memuat satu laporan berdasarkan nama
    case 'load':
        $reportName = $_GET['reportName'] ?? '';
        $stmt = $conn->prepare("SELECT report_data FROM pivot_reports WHERE report_name = ?");
        $stmt->bind_param("s", $reportName);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        // Syncfusion mengharapkan report data dikembalikan dalam format string, bukan objek JSON
        echo $result['report_data'] ?? '{}';
        break;
        
    // Aksi untuk menyimpan laporan
    case 'save':
        $reportName = $_POST['reportName'] ?? '';
        $reportData = $_POST['report'] ?? '';
        
        // Cek dulu apakah nama sudah ada (untuk menentukan INSERT atau UPDATE)
        $stmt_check = $conn->prepare("SELECT id FROM pivot_reports WHERE report_name = ?");
        $stmt_check->bind_param("s", $reportName);
        $stmt_check->execute();
        $result_check = $stmt_check->get_result();
        
        if ($result_check->num_rows > 0) {
            // Jika sudah ada, UPDATE
            $stmt = $conn->prepare("UPDATE pivot_reports SET report_data = ? WHERE report_name = ?");
            $stmt->bind_param("ss", $reportData, $reportName);
        } else {
            // Jika belum ada, INSERT
            $stmt = $conn->prepare("INSERT INTO pivot_reports (report_name, report_data) VALUES (?, ?)");
            $stmt->bind_param("ss", $reportName, $reportData);
        }
        
        if ($stmt->execute()) {
            echo json_encode(['status' => 'success', 'message' => 'Laporan berhasil disimpan']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan laporan: ' . $stmt->error]);
        }
        break;
        
    // Aksi untuk menghapus laporan
    case 'remove':
        $reportName = $_POST['reportName'] ?? '';
        $stmt = $conn->prepare("DELETE FROM pivot_reports WHERE report_name = ?");
        $stmt->bind_param("s", $reportName);
        
        if ($stmt->execute()) {
            echo json_encode(['status' => 'success', 'message' => 'Laporan berhasil dihapus']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal menghapus laporan']);
        }
        break;
        
    // Aksi untuk mengubah nama laporan
    case 'rename':
        $oldName = $_POST['oldReportName'] ?? '';
        $newName = $_POST['newReportName'] ?? '';
        $stmt = $conn->prepare("UPDATE pivot_reports SET report_name = ? WHERE report_name = ?");
        $stmt->bind_param("ss", $newName, $oldName);
        
        if ($stmt->execute()) {
            echo json_encode(['status' => 'success', 'message' => 'Nama laporan berhasil diubah']);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal mengubah nama laporan']);
        }
        break;
        
    default:
        echo json_encode(['status' => 'error', 'message' => 'Aksi tidak valid']);
        break;
}

$conn->close();
?>