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

// Error reporting untuk development
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Header untuk response JSON
header('Content-Type: application/json');

try {
    // Koneksi dengan error handling
    // $conn = new mysqli($host, $user, $pass, $db);
include_once '../data.php';
$conn = new mysqli($servername, $username, $password, $dbname);    
    if ($conn->connect_error) {
        throw new Exception("Koneksi database 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(100) 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);

    // Ambil aksi dari request
    $action = isset($_REQUEST['action']) ? $_REQUEST['action'] : '';

    switch ($action) {
        case 'save':
            // Simpan template baru
            $reportName = isset($_POST['reportName']) ? $_POST['reportName'] : '';
            $reportData = isset($_POST['report']) ? $_POST['report'] : '';
            
            if (empty($reportName) || empty($reportData)) {
                echo json_encode(['status' => 'error', 'message' => 'Nama template dan data template harus diisi']);
                exit;
            }
            
            // Cek apakah template sudah ada
            $checkQuery = "SELECT id FROM pivot_reports WHERE report_name = ?";
            $stmt = $conn->prepare($checkQuery);
            $stmt->bind_param("s", $reportName);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                // Update template yang sudah ada
                $updateQuery = "UPDATE pivot_reports SET report_data = ? WHERE report_name = ?";
                $stmt = $conn->prepare($updateQuery);
                $stmt->bind_param("ss", $reportData, $reportName);
                $success = $stmt->execute();
            } else {
                // Insert template baru
                $insertQuery = "INSERT INTO pivot_reports (report_name, report_data) VALUES (?, ?)";
                $stmt = $conn->prepare($insertQuery);
                $stmt->bind_param("ss", $reportName, $reportData);
                $success = $stmt->execute();
            }
            
            if ($success) {
                echo json_encode(['status' => 'success', 'message' => 'Template berhasil disimpan']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan template: ' . $conn->error]);
            }
            break;
            
        case 'load':
            // Muat template berdasarkan nama
            $reportName = isset($_GET['reportName']) ? $_GET['reportName'] : '';
            
            if (empty($reportName)) {
                echo json_encode(['status' => 'error', 'message' => 'Nama template tidak valid']);
                exit;
            }
            
            $query = "SELECT report_data FROM pivot_reports WHERE report_name = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("s", $reportName);
            $stmt->execute();
            $result = $stmt->get_result();
            
            if ($result->num_rows > 0) {
                $row = $result->fetch_assoc();
                echo $row['report_data'];
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Template tidak ditemukan']);
            }
            break;
            
        case 'rename':
            // Ubah nama template
            $oldName = isset($_POST['oldReportName']) ? $_POST['oldReportName'] : '';
            $newName = isset($_POST['newReportName']) ? $_POST['newReportName'] : '';
            
            if (empty($oldName) || empty($newName)) {
                echo json_encode(['status' => 'error', 'message' => 'Nama lama dan nama baru harus diisi']);
                exit;
            }
            
            $query = "UPDATE pivot_reports SET report_name = ? WHERE report_name = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("ss", $newName, $oldName);
            $success = $stmt->execute();
            
            if ($success) {
                echo json_encode(['status' => 'success', 'message' => 'Template berhasil diubah namanya']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Gagal mengubah nama template: ' . $conn->error]);
            }
            break;
            
        case 'remove':
            // Hapus template
            $reportName = isset($_POST['reportName']) ? $_POST['reportName'] : '';
            
            if (empty($reportName)) {
                echo json_encode(['status' => 'error', 'message' => 'Nama template tidak valid']);
                exit;
            }
            
            $query = "DELETE FROM pivot_reports WHERE report_name = ?";
            $stmt = $conn->prepare($query);
            $stmt->bind_param("s", $reportName);
            $success = $stmt->execute();
            
            if ($success) {
                echo json_encode(['status' => 'success', 'message' => 'Template berhasil dihapus']);
            } else {
                echo json_encode(['status' => 'error', 'message' => 'Gagal menghapus template: ' . $conn->error]);
            }
            break;
            
        case 'fetch':
            // Ambil semua nama template
            $query = "SELECT report_name FROM pivot_reports ORDER BY report_name ASC";
            $result = $conn->query($query);
            
            $reportNames = [];
            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    $reportNames[] = $row['report_name'];
                }
            }
            
            echo json_encode($reportNames);
            break;
            
        default:
            echo json_encode(['status' => 'error', 'message' => 'Aksi tidak valid']);
            break;
    }

    $conn->close();
} catch (Exception $e) {
    echo json_encode(['status' => 'error', 'message' => $e->getMessage()]);
}
?>