<?php
// Aktifkan error reporting
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $tabel = $_POST['tabel'] ?? '';
    $id = $_POST['id'] ?? '';

    // Validasi input
    include '../config/connect.php';
    include '../config/routeros_api.class.php';

    // Array untuk menyimpan daftar data yang dihapus
    $deletedItems = [];
    $totalDeleted = 0;

    // Apabila yang dihapus adalah pelanggan
    if ($tabel === 'pelanggan') {
        // Ambil data pelanggan
        $stmt = $pdo->prepare("SELECT id_setting_mikrotik, akun, jenis_layanan FROM pelanggan WHERE id = :id");
        $stmt->bindParam(':id', $id, PDO::PARAM_INT);
        $stmt->execute();
        $data = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if ($data === false) {
            echo json_encode(['success' => false, 'error' => 'Data pelanggan tidak ditemukan']);
            exit;
        }

        $user = $data['akun'];

        // Get Mikrotik Setting
        $Mikro = $pdo->prepare("SELECT ip_address, port_api, username, password FROM setting_mikrotik WHERE id = :idset");
        $Mikro->bindParam(':idset', $data['id_setting_mikrotik'], PDO::PARAM_INT);
        $Mikro->execute();
        $Mikrot = $Mikro->fetch(PDO::FETCH_ASSOC);
        
        if ($Mikrot === false) {
            echo json_encode(['success' => false, 'error' => 'Setting Mikrotik tidak ditemukan']);
            exit;
        }

        $m_ip = $Mikrot['ip_address'];
        $m_user = $Mikrot['username'];
        $m_pass = $Mikrot['password'];
        $m_port = $Mikrot['port_api'];

        $API = new RouterosAPI();
        $API->debug = false;

        if ($API->connect2($m_ip, $m_user, $m_pass, $m_port)) {
            if ($data['jenis_layanan'] == 'Hotspot') {
                $arrIDh = $API->comm("/ip/hotspot/user/getall", [
                    ".proplist" => ".id",
                    "?name" => $user,
                ]);
                
                if (!empty($arrIDh)) {
                    $API->comm("/ip/hotspot/user/remove", [
                        ".id" => $arrIDh[0][".id"],
                    ]);
                    $deletedItems[] = ['table' => 'hotspot', 'count' => 1];
                    $totalDeleted++;
                }
            } else {
                $arrID = $API->comm("/ppp/secret/getall", [
                    ".proplist" => ".id",
                    "?name" => $user,
                ]);
                
                if (!empty($arrID)) {
                    $API->comm("/ppp/secret/remove", [
                        ".id" => $arrID[0][".id"],
                    ]);
                    $deletedItems[] = ['table' => 'ppp_secret', 'count' => 1];
                    $totalDeleted++;
                }
            }

            // Menyiapkan perintah SQL untuk menghapus data tagihan
            $sql1 = "DELETE FROM tagihan WHERE id_pelanggan = ?";
            $stmt = $pdo->prepare($sql1);
            $stmt->bindParam(1, $id, PDO::PARAM_INT);
            $stmt->execute();
            $deletedTagihanCount = $stmt->rowCount();

            if ($deletedTagihanCount > 0) {
                $deletedItems[] = ['table' => 'tagihan', 'count' => $deletedTagihanCount];
                $totalDeleted += $deletedTagihanCount;
            }

            // Menyiapkan perintah SQL untuk menghapus data tiket gangguan
            $sql2 = "DELETE FROM tiket_gangguan WHERE id_pelanggan = ?";
            $stmt = $pdo->prepare($sql2);
            $stmt->bindParam(1, $id, PDO::PARAM_INT);
            $stmt->execute();
            $deletedTiketCount = $stmt->rowCount();

            if ($deletedTiketCount > 0) {
                $deletedItems[] = ['table' => 'tiket_gangguan', 'count' => $deletedTiketCount];
                $totalDeleted += $deletedTiketCount;
            }

            // Menyiapkan perintah SQL untuk menghapus data dari tabel utama
            $sql = "DELETE FROM pelanggan WHERE id = ?";
            $stmt = $pdo->prepare($sql);
            $stmt->bindParam(1, $id, PDO::PARAM_INT);
            $stmt->execute();

            // Menyiapkan respons JSON
            $response = [
                'success' => true,
                'deleted_count' => $totalDeleted,
                'deleted_items' => $deletedItems
            ];

        } else {
            echo json_encode(['success' => false, 'error' => 'Mikrotik tidak terhubung']);
            exit;
        }
    } else {
        // Menyiapkan perintah SQL untuk menghapus data dari tabel lain
        $sql = "DELETE FROM $tabel WHERE id = ?";
        $stmt = $pdo->prepare($sql);
        $stmt->bindParam(1, $id, PDO::PARAM_INT);
        
        if ($stmt->execute()) {
            $deletedCount = $stmt->rowCount();
            $response = [
                'success' => true,
                'deleted_count' => $deletedCount,
                'deleted_items' => [['table' => 'data yang anda hapus', 'count' => $deletedCount]]
            ];
        } else {
            $response = ['success' => false, 'error' => 'Gagal menghapus data'];
        }
    }

    $stmt->closeCursor();
    $pdo = null; // Menutup koneksi PDO

    header('Content-Type: application/json');
    echo json_encode($response);
} else {
    header('Content-Type: application/json');
    echo json_encode(['success' => false, 'error' => 'Invalid request method']);
}

?>