<?php
// Start session
session_start();

// Include database connection
require_once "../config/connection.php";

// Redirect if not IT user - using functions from connection.php
if (!is_logged_in() || !is_user_type('it')) {
    header("Location: ../login.php");
    exit();
}

// Get IT user data
$it_id = $_SESSION['user_id'];
$stmt = $conn->prepare("SELECT * FROM it_users WHERE id = ?");
$stmt->bind_param("i", $it_id);
$stmt->execute();
$it_data = $stmt->get_result()->fetch_assoc();
$stmt->close();

// Set page title
$page_title = "Pengelolaan Buyer & Collection";

// Process form for adding collection to existing buyer
if (isset($_POST['add_collection'])) {
    $buyer_id = $_POST['buyer_id'];
    $collection_name = $_POST['collection_name'];
    
    // Validate input
    if (empty($collection_name)) {
        $error_message = "Nama collection tidak boleh kosong";
    } else {
        // Check if collection already exists for this buyer
        $check_stmt = $conn->prepare("SELECT * FROM collections WHERE nama_collection = ? AND buyer_id = ?");
        $check_stmt->bind_param("si", $collection_name, $buyer_id);
        $check_stmt->execute();
        $result = $check_stmt->get_result();
        
        if ($result->num_rows > 0) {
            $error_message = "Collection dengan nama tersebut sudah ada untuk buyer ini";
        } else {
            // Insert new collection
            $insert_stmt = $conn->prepare("INSERT INTO collections (nama_collection, buyer_id) VALUES (?, ?)");
            $insert_stmt->bind_param("si", $collection_name, $buyer_id);
            
            if ($insert_stmt->execute()) {
                $success_message = "Collection baru berhasil ditambahkan";
                // Log activity
                log_activity($conn, $it_id, 'it', 'Collection Added', "IT user added new collection '$collection_name' for buyer ID: $buyer_id");
            } else {
                $error_message = "Gagal menambahkan collection: " . $conn->error;
            }
            $insert_stmt->close();
        }
        $check_stmt->close();
    }
}

// Process form for adding new buyer with collection
if (isset($_POST['add_buyer'])) {
    $buyer_name = $_POST['buyer_name'];
    $buyer_code = $_POST['buyer_code'];
    $collection_name = $_POST['new_collection_name'];
    
    // Validate input
    if (empty($buyer_name) || empty($buyer_code) || empty($collection_name)) {
        $error_message_new = "Semua field harus diisi";
    } else {
        // Check if buyer code already exists
        $check_stmt = $conn->prepare("SELECT * FROM buyers WHERE kode_buyer = ?");
        $check_stmt->bind_param("s", $buyer_code);
        $check_stmt->execute();
        $result = $check_stmt->get_result();
        
        if ($result->num_rows > 0) {
            $error_message_new = "Kode buyer sudah digunakan";
        } else {
            // Begin transaction
            $conn->begin_transaction();
            
            try {
                // Insert new buyer
                $insert_buyer = $conn->prepare("INSERT INTO buyers (nama_buyer, kode_buyer) VALUES (?, ?)");
                $insert_buyer->bind_param("ss", $buyer_name, $buyer_code);
                $insert_buyer->execute();
                $new_buyer_id = $conn->insert_id;
                
                // Insert new collection for this buyer
                $insert_collection = $conn->prepare("INSERT INTO collections (nama_collection, buyer_id) VALUES (?, ?)");
                $insert_collection->bind_param("si", $collection_name, $new_buyer_id);
                $insert_collection->execute();
                
                // Commit transaction
                $conn->commit();
                
                $success_message_new = "Buyer baru dan collection berhasil ditambahkan";
                // Log activity
                log_activity($conn, $it_id, 'it', 'Buyer and Collection Added', "IT user added new buyer '$buyer_name' with collection '$collection_name'");
                
            } catch (Exception $e) {
                // Rollback in case of error
                $conn->rollback();
                $error_message_new = "Gagal menambahkan data: " . $e->getMessage();
            }
        }
        $check_stmt->close();
    }
}

// Handle AJAX delete requests for collections
if (isset($_POST['action']) && $_POST['action'] == 'delete_collection') {
    $collection_id = $_POST['collection_id'];
    $response = array();
    
    try {
        // Begin transaction for safety
        $conn->begin_transaction();
        
        // Check if collection is used in any transactions
        $check_stmt = $conn->prepare("
            SELECT COUNT(*) as count
            FROM stock_transactions t
            WHERE t.collection_id = ?
        ");
        $check_stmt->bind_param("i", $collection_id);
        $check_stmt->execute();
        $count_result = $check_stmt->get_result()->fetch_assoc();
        $check_stmt->close();
        
        if ($count_result['count'] > 0) {
            // Collection is used in transactions, can't delete
            $response['status'] = 'error';
            $response['message'] = 'Collection tidak dapat dihapus karena terhubung dengan transaksi';
            $conn->rollback();
        } else {
            // Check if collection is used in master_color_panel
            $check_color_stmt = $conn->prepare("
                SELECT COUNT(*) as count
                FROM master_color_panel mcp
                WHERE mcp.collection_id = ?
            ");
            $check_color_stmt->bind_param("i", $collection_id);
            $check_color_stmt->execute();
            $color_count = $check_color_stmt->get_result()->fetch_assoc();
            $check_color_stmt->close();
            
            if ($color_count['count'] > 0) {
                $response['status'] = 'error';
                $response['message'] = 'Collection tidak dapat dihapus karena terhubung dengan color panel';
                $conn->rollback();
            } else {
                // Safe to delete
                $delete_stmt = $conn->prepare("DELETE FROM collections WHERE id = ?");
                $delete_stmt->bind_param("i", $collection_id);
                
                if ($delete_stmt->execute() && $delete_stmt->affected_rows > 0) {
                    $conn->commit();
                    $response['status'] = 'success';
                    $response['message'] = 'Collection berhasil dihapus';
                    // Log activity
                    log_activity($conn, $it_id, 'it', 'Collection Deleted', "IT user deleted collection ID: $collection_id");
                } else {
                    $conn->rollback();
                    $response['status'] = 'error';
                    $response['message'] = 'Collection tidak ditemukan atau gagal dihapus';
                }
                $delete_stmt->close();
            }
        }
        
    } catch (Exception $e) {
        $conn->rollback();
        $response['status'] = 'error';
        $response['message'] = 'Terjadi kesalahan: ' . $e->getMessage();
        error_log("Delete collection error: " . $e->getMessage());
    }
    
    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}

// Handle AJAX delete requests for buyers
if (isset($_POST['action']) && $_POST['action'] == 'delete_buyer') {
    $buyer_id = $_POST['buyer_id'];
    $response = array();
    
    try {
        // Begin transaction
        $conn->begin_transaction();
        
        // Check if any collections from this buyer are used in transactions
        $check_stmt = $conn->prepare("
            SELECT COUNT(*) as count
            FROM stock_transactions t
            JOIN collections c ON t.collection_id = c.id
            WHERE c.buyer_id = ?
        ");
        $check_stmt->bind_param("i", $buyer_id);
        $check_stmt->execute();
        $transaction_count = $check_stmt->get_result()->fetch_assoc();
        $check_stmt->close();
        
        if ($transaction_count['count'] > 0) {
            // Buyer's collections are used in transactions, can't delete
            $response['status'] = 'error';
            $response['message'] = 'Buyer tidak dapat dihapus karena collection-nya terhubung dengan transaksi';
            $conn->rollback();
        } else {
            // Check if any color panels are associated with this buyer
            $check_color_stmt = $conn->prepare("
                SELECT COUNT(*) as count
                FROM master_color_panel mcp
                WHERE mcp.buyer_id = ?
            ");
            $check_color_stmt->bind_param("i", $buyer_id);
            $check_color_stmt->execute();
            $color_count = $check_color_stmt->get_result()->fetch_assoc();
            $check_color_stmt->close();
            
            if ($color_count['count'] > 0) {
                // Check if any of these color panels have stock items
                $check_items_stmt = $conn->prepare("
                    SELECT COUNT(*) as count
                    FROM color_stock_items csi
                    JOIN master_color_panel mcp ON csi.color_id = mcp.id
                    WHERE mcp.buyer_id = ?
                ");
                $check_items_stmt->bind_param("i", $buyer_id);
                $check_items_stmt->execute();
                $items_count = $check_items_stmt->get_result()->fetch_assoc();
                $check_items_stmt->close();
                
                if ($items_count['count'] > 0) {
                    $response['status'] = 'error';
                    $response['message'] = 'Buyer tidak dapat dihapus karena memiliki stock items';
                    $conn->rollback();
                } else {
                    // Delete color panel components first
                    $delete_components = $conn->prepare("
                        DELETE cpc FROM color_panel_components cpc
                        JOIN master_color_panel mcp ON cpc.color_id = mcp.id
                        WHERE mcp.buyer_id = ?
                    ");
                    $delete_components->bind_param("i", $buyer_id);
                    $delete_components->execute();
                    $delete_components->close();
                    
                    // Delete color panels
                    $delete_panels = $conn->prepare("DELETE FROM master_color_panel WHERE buyer_id = ?");
                    $delete_panels->bind_param("i", $buyer_id);
                    $delete_panels->execute();
                    $delete_panels->close();
                    
                    // Delete all collections for this buyer
                    $delete_collections = $conn->prepare("DELETE FROM collections WHERE buyer_id = ?");
                    $delete_collections->bind_param("i", $buyer_id);
                    $delete_collections->execute();
                    $delete_collections->close();
                    
                    // Delete the buyer
                    $delete_buyer = $conn->prepare("DELETE FROM buyers WHERE id = ?");
                    $delete_buyer->bind_param("i", $buyer_id);
                    
                    if ($delete_buyer->execute() && $delete_buyer->affected_rows > 0) {
                        $conn->commit();
                        $response['status'] = 'success';
                        $response['message'] = 'Buyer dan semua data terkaitnya berhasil dihapus';
                        // Log activity
                        log_activity($conn, $it_id, 'it', 'Buyer Deleted', "IT user deleted buyer ID: $buyer_id");
                    } else {
                        $conn->rollback();
                        $response['status'] = 'error';
                        $response['message'] = 'Buyer tidak ditemukan atau gagal dihapus';
                    }
                    $delete_buyer->close();
                }
            } else {
                // No color panels, safe to delete collections and buyer
                // Delete all collections for this buyer
                $delete_collections = $conn->prepare("DELETE FROM collections WHERE buyer_id = ?");
                $delete_collections->bind_param("i", $buyer_id);
                $delete_collections->execute();
                $delete_collections->close();
                
                // Delete the buyer
                $delete_buyer = $conn->prepare("DELETE FROM buyers WHERE id = ?");
                $delete_buyer->bind_param("i", $buyer_id);
                
                if ($delete_buyer->execute() && $delete_buyer->affected_rows > 0) {
                    $conn->commit();
                    $response['status'] = 'success';
                    $response['message'] = 'Buyer dan semua collection-nya berhasil dihapus';
                    // Log activity
                    log_activity($conn, $it_id, 'it', 'Buyer Deleted', "IT user deleted buyer ID: $buyer_id");
                } else {
                    $conn->rollback();
                    $response['status'] = 'error';
                    $response['message'] = 'Buyer tidak ditemukan atau gagal dihapus';
                }
                $delete_buyer->close();
            }
        }
        
    } catch (Exception $e) {
        $conn->rollback();
        $response['status'] = 'error';
        $response['message'] = 'Terjadi kesalahan: ' . $e->getMessage();
        error_log("Delete buyer error: " . $e->getMessage());
    }
    
    // Return JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}

// Fetch all buyers for dropdown
$buyers_query = $conn->query("SELECT * FROM buyers ORDER BY nama_buyer");

// Include header
include '../template_it/header.php';
?>

<!-- Main Content Area -->
<main class="flex-1 p-6 overflow-auto bg-gradient-to-br from-blue-100 via-teal-100 to-green-100">
    <div class="mb-6">
        <h1 class="text-2xl font-bold text-gray-800">Pengelolaan Buyer & Collection</h1>
        <p class="text-gray-600">Kelola data buyer dan collection untuk sistem color panel</p>
    </div>
    
    <!-- Tabs -->
    <div class="mb-6">
        <div class="border-b border-gray-200">
            <ul class="flex flex-wrap -mb-px text-sm font-medium text-center">
                <li class="mr-2">
                    <a href="#" class="inline-flex items-center justify-center p-4 text-blue-600 border-b-2 border-blue-600 rounded-t-lg active group tab-button" data-tab="existing-buyer">
                        <i class="fas fa-user-tag mr-2"></i>Buyer dengan Collection Baru
                    </a>
                </li>
                <li class="mr-2">
                    <a href="#" class="inline-flex items-center justify-center p-4 text-gray-500 hover:text-gray-600 hover:border-gray-300 border-b-2 border-transparent rounded-t-lg group tab-button" data-tab="new-buyer">
                        <i class="fas fa-user-plus mr-2"></i>Buyer Baru dengan Collection Baru
                    </a>
                </li>
            </ul>
        </div>
    </div>
    
    <!-- Existing Buyer - New Collection Tab -->
    <div id="existing-buyer-tab" class="tab-content">
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">Tambah Collection untuk Buyer yang Sudah Ada</h2>
            
            <?php if (isset($error_message)): ?>
                <div class="mb-4 p-4 bg-red-100 border-l-4 border-red-500 text-red-700">
                    <p><?php echo $error_message; ?></p>
                </div>
            <?php endif; ?>
            
            <?php if (isset($success_message)): ?>
                <div class="mb-4 p-4 bg-green-100 border-l-4 border-green-500 text-green-700">
                    <p><?php echo $success_message; ?></p>
                </div>
            <?php endif; ?>
            
            <form action="" method="POST" class="space-y-4">
                <div>
                    <label for="buyer_id" class="block text-sm font-medium text-gray-700 mb-1">Pilih Buyer</label>
                    <select id="buyer_id" name="buyer_id" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50">
                        <option value="">-- Pilih Buyer --</option>
                        <?php while ($buyer = $buyers_query->fetch_assoc()): ?>
                            <option value="<?php echo $buyer['id']; ?>">
                                <?php echo htmlspecialchars($buyer['nama_buyer'] . ' (' . $buyer['kode_buyer'] . ')'); ?>
                            </option>
                        <?php endwhile; ?>
                    </select>
                </div>
                
                <div>
                    <label for="collection_name" class="block text-sm font-medium text-gray-700 mb-1">Nama Collection Baru</label>
                    <input type="text" id="collection_name" name="collection_name" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50" placeholder="Masukkan nama collection">
                </div>
                
                <div class="pt-3">
                    <button type="submit" name="add_collection" class="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50">
                        <i class="fas fa-plus-circle mr-2"></i>Tambah Collection
                    </button>
                </div>
            </form>
            
            <!-- Display Existing Collections -->
            <div class="mt-8">
                <h3 class="text-lg font-medium text-gray-800 mb-3">Collection yang Sudah Ada</h3>
                
                <!-- Notification container for collection delete -->
                <div id="collection-notification" class="hidden mb-4"></div>
                
                <div class="overflow-x-auto">
                    <table class="min-w-full bg-white border border-gray-200">
                        <thead class="bg-gray-100">
                            <tr>
                                <th class="py-2 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase">ID</th>
                                <th class="py-2 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase">Buyer</th>
                                <th class="py-2 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase">Kode</th>
                                <th class="py-2 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase">Collection</th>
                                <th class="py-2 px-4 border-b text-center text-xs font-medium text-gray-500 uppercase">Aksi</th>
                            </tr>
                        </thead>
                        <tbody id="collection-table-body">
                            <?php
                            // Get all collections with buyer information
                            $collections_query = $conn->query("
                                SELECT c.id, c.nama_collection, b.nama_buyer, b.kode_buyer, b.id AS buyer_id
                                FROM collections c
                                JOIN buyers b ON c.buyer_id = b.id
                                ORDER BY b.nama_buyer, c.nama_collection
                            ");
                            
                            while ($collection = $collections_query->fetch_assoc()):
                            ?>
                            <tr class="hover:bg-gray-50" id="collection-row-<?php echo $collection['id']; ?>">
                                <td class="py-2 px-4 border-b"><?php echo $collection['id']; ?></td>
                                <td class="py-2 px-4 border-b"><?php echo htmlspecialchars($collection['nama_buyer']); ?></td>
                                <td class="py-2 px-4 border-b"><?php echo htmlspecialchars($collection['kode_buyer']); ?></td>
                                <td class="py-2 px-4 border-b"><?php echo htmlspecialchars($collection['nama_collection']); ?></td>
                                <td class="py-2 px-4 border-b text-center">
                                    <button 
                                        type="button" 
                                        class="delete-collection-btn px-3 py-1 bg-red-500 text-white rounded-md hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-opacity-50"
                                        data-id="<?php echo $collection['id']; ?>"
                                        data-buyer-id="<?php echo $collection['buyer_id']; ?>"
                                    >
                                        <i class="fas fa-trash-alt"></i> Hapus
                                    </button>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
    
    <!-- New Buyer - New Collection Tab -->
    <div id="new-buyer-tab" class="tab-content hidden">
        <div class="bg-white rounded-lg shadow-md p-6 mb-6">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">Tambah Buyer Baru dengan Collection Baru</h2>
            
            <?php if (isset($error_message_new)): ?>
                <div class="mb-4 p-4 bg-red-100 border-l-4 border-red-500 text-red-700">
                    <p><?php echo $error_message_new; ?></p>
                </div>
            <?php endif; ?>
            
            <?php if (isset($success_message_new)): ?>
                <div class="mb-4 p-4 bg-green-100 border-l-4 border-green-500 text-green-700">
                    <p><?php echo $success_message_new; ?></p>
                </div>
            <?php endif; ?>
            
            <form action="" method="POST" class="space-y-4">
                <div>
                    <label for="buyer_name" class="block text-sm font-medium text-gray-700 mb-1">Nama Buyer Baru</label>
                    <input type="text" id="buyer_name" name="buyer_name" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50" placeholder="Masukkan nama buyer">
                </div>
                
                <div>
                    <label for="buyer_code" class="block text-sm font-medium text-gray-700 mb-1">Kode Buyer (max 5 karakter)</label>
                    <input type="text" id="buyer_code" name="buyer_code" maxlength="5" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50" placeholder="Contoh: EA, CB, UT">
                    <p class="mt-1 text-sm text-gray-500">Kode buyer harus unik, maksimal 5 karakter</p>
                </div>
                
                <div>
                    <label for="new_collection_name" class="block text-sm font-medium text-gray-700 mb-1">Nama Collection Baru</label>
                    <input type="text" id="new_collection_name" name="new_collection_name" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50" placeholder="Masukkan nama collection">
                </div>
                
                <div class="pt-3">
                    <button type="submit" name="add_buyer" class="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 focus:ring-opacity-50">
                        <i class="fas fa-user-plus mr-2"></i>Tambah Buyer dan Collection
                    </button>
                </div>
            </form>
            
            <!-- Display Existing Buyers -->
            <div class="mt-8">
                <h3 class="text-lg font-medium text-gray-800 mb-3">Buyer yang Sudah Ada</h3>
                
                <!-- Notification container for buyer delete -->
                <div id="buyer-notification" class="hidden mb-4"></div>
                
                <div class="overflow-x-auto">
                    <table class="min-w-full bg-white border border-gray-200">
                        <thead class="bg-gray-100">
                            <tr>
                                <th class="py-2 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase">ID</th>
                                <th class="py-2 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase">Nama Buyer</th>
                                <th class="py-2 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase">Kode Buyer</th>
                                <th class="py-2 px-4 border-b text-left text-xs font-medium text-gray-500 uppercase">Total Collection</th>
                                <th class="py-2 px-4 border-b text-center text-xs font-medium text-gray-500 uppercase">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            // Reset the query pointer
                            $buyers_query->data_seek(0);
                            
                            while ($buyer = $buyers_query->fetch_assoc()):
                                // Count collections for this buyer
                                $count_stmt = $conn->prepare("SELECT COUNT(*) as total FROM collections WHERE buyer_id = ?");
                                $count_stmt->bind_param("i", $buyer['id']);
                                $count_stmt->execute();
                                $count_result = $count_stmt->get_result()->fetch_assoc();
                                $count_stmt->close();
                            ?>
                            <tr class="hover:bg-gray-50" id="buyer-row-<?php echo $buyer['id']; ?>">
                                <td class="py-2 px-4 border-b"><?php echo $buyer['id']; ?></td>
                                <td class="py-2 px-4 border-b"><?php echo htmlspecialchars($buyer['nama_buyer']); ?></td>
                                <td class="py-2 px-4 border-b"><?php echo htmlspecialchars($buyer['kode_buyer']); ?></td>
                                <td class="py-2 px-4 border-b"><?php echo $count_result['total']; ?></td>
                                <td class="py-2 px-4 border-b text-center">
                                    <button 
                                        type="button" 
                                        class="delete-buyer-btn px-3 py-1 bg-red-500 text-white rounded-md hover:bg-red-600 focus:outline-none focus:ring-2 focus:ring-red-500 focus:ring-opacity-50"
                                        data-id="<?php echo $buyer['id']; ?>"
                                    >
                                        <i class="fas fa-trash-alt"></i> Hapus
                                    </button>
                                </td>
                            </tr>
                            <?php endwhile; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</main>

<!-- JavaScript for tab functionality and delete operations - IMPROVED VERSION -->
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Get all tab buttons
    const tabButtons = document.querySelectorAll('.tab-button');
    
    // Add click event to each tab button
    tabButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            
            const tabName = this.getAttribute('data-tab');
            switchTab(tabName);
        });
    });
    
    // Function to switch tabs
    function switchTab(tabName) {
        // Hide all tab contents
        document.querySelectorAll('.tab-content').forEach(tab => {
            tab.classList.add('hidden');
        });
        
        // Show the selected tab content
        const selectedTab = document.getElementById(tabName + '-tab');
        if (selectedTab) {
            selectedTab.classList.remove('hidden');
        }
        
        // Reset all tab buttons to inactive state
        tabButtons.forEach(btn => {
            btn.classList.remove('text-blue-600', 'border-blue-600');
            btn.classList.add('text-gray-500', 'border-transparent');
        });
        
        // Set active tab button
        const activeButton = document.querySelector(`.tab-button[data-tab="${tabName}"]`);
        if (activeButton) {
            activeButton.classList.remove('text-gray-500', 'border-transparent');
            activeButton.classList.add('text-blue-600', 'border-blue-600');
        }
    }
    
    // Function to show notification - IMPROVED VERSION
    function showNotification(containerId, type, message) {
        const container = document.getElementById(containerId);
        if (!container) {
            console.error(`Notification container with ID "${containerId}" not found`);
            return;
        }
        
        // Set appropriate classes based on notification type
        container.className = `mb-4 p-4 border-l-4 ${
            type === 'success' 
                ? 'bg-green-100 border-green-500 text-green-700' 
                : 'bg-red-100 border-red-500 text-red-700'
        }`;
        
        // Set notification message
        container.innerHTML = `<p>${message}</p>`;
        
        // Make notification visible
        container.classList.remove('hidden');
        
        // Scroll to notification to ensure it's visible
        container.scrollIntoView({ behavior: 'smooth', block: 'start' });
        
        // Hide notification after 5 seconds
        setTimeout(() => {
            container.classList.add('hidden');
        }, 5000);
    }
    
    // Process AJAX response - IMPROVED Helper function
    function processResponse(xhr, containerId, rowElement) {
        console.log('Response received:', xhr.responseText); // Debug log
        
        try {
            const response = JSON.parse(xhr.responseText);
            
            if (response.status === 'success') {
                // Only remove row from display if database operation was successful
                rowElement.style.transition = 'opacity 0.5s';
                rowElement.style.opacity = '0';
                
                setTimeout(() => {
                    rowElement.remove();
                    showNotification(containerId, 'success', response.message);
                }, 500);
                
                return { success: true, response: response };
            } else {
                // Show specific error from server
                showNotification(containerId, 'error', response.message);
                return { success: false, response: response };
            }
        } catch (e) {
            console.error('Response parsing error:', e);
            console.error('Raw response:', xhr.responseText);
            
            // Check for specific database errors in the response
            if (xhr.responseText.includes('foreign key constraint') || 
                xhr.responseText.includes('Cannot delete or update a parent row')) {
                showNotification(containerId, 'error', 'Data tidak dapat dihapus karena terhubung dengan data lain');
            } else {
                showNotification(containerId, 'error', 'Terjadi kesalahan saat menghapus data');
            }
            return { success: false };
        }
    }
    
    // Delete Collection functionality - IMPROVED VERSION
    const deleteCollectionButtons = document.querySelectorAll('.delete-collection-btn');
    if (deleteCollectionButtons.length > 0) {
        deleteCollectionButtons.forEach(button => {
            button.addEventListener('click', function() {
                if (confirm('Apakah Anda yakin ingin menghapus collection ini?')) {
                    const collectionId = this.getAttribute('data-id');
                    const rowElement = document.getElementById('collection-row-' + collectionId);
                    
                    if (!rowElement) {
                        console.error(`Row with ID "collection-row-${collectionId}" not found`);
                        return;
                    }
                    
                    // Disable button to prevent multiple clicks
                    this.disabled = true;
                    this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Menghapus...';
                    
                    // Send AJAX request to delete the collection
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', window.location.href, true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    
                    xhr.onload = function() {
                        const result = processResponse(xhr, 'collection-notification', rowElement);
                        
                        // Re-enable button if operation failed
                        if (!result.success) {
                            button.disabled = false;
                            button.innerHTML = '<i class="fas fa-trash-alt"></i> Hapus';
                        }
                    };
                    
                    xhr.onerror = function() {
                        showNotification('collection-notification', 'error', 'Gagal menghubungi server');
                        button.disabled = false;
                        button.innerHTML = '<i class="fas fa-trash-alt"></i> Hapus';
                    };
                    
                    xhr.send('action=delete_collection&collection_id=' + collectionId);
                }
            });
        });
    }
    
    // Delete Buyer functionality - IMPROVED VERSION
    const deleteBuyerButtons = document.querySelectorAll('.delete-buyer-btn');
    if (deleteBuyerButtons.length > 0) {
        deleteBuyerButtons.forEach(button => {
            button.addEventListener('click', function() {
                if (confirm('Apakah Anda yakin ingin menghapus buyer ini? Semua collection milik buyer ini juga akan dihapus.')) {
                    const buyerId = this.getAttribute('data-id');
                    const rowElement = document.getElementById('buyer-row-' + buyerId);
                    
                    if (!rowElement) {
                        console.error(`Row with ID "buyer-row-${buyerId}" not found`);
                        return;
                    }
                    
                    // Disable button to prevent multiple clicks
                    this.disabled = true;
                    this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Menghapus...';
                    
                    // Send AJAX request to delete the buyer
                    const xhr = new XMLHttpRequest();
                    xhr.open('POST', window.location.href, true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                    
                    xhr.onload = function() {
                        const result = processResponse(xhr, 'buyer-notification', rowElement);
                        
                        // If deletion was successful, also remove related collection rows
                        if (result.success) {
                            const collectionRows = document.querySelectorAll(`.delete-collection-btn[data-buyer-id="${buyerId}"]`);
                            collectionRows.forEach(collectionButton => {
                                const collectionId = collectionButton.getAttribute('data-id');
                                const collectionRow = document.getElementById('collection-row-' + collectionId);
                                if (collectionRow) {
                                    collectionRow.style.transition = 'opacity 0.5s';
                                    collectionRow.style.opacity = '0';
                                    setTimeout(() => {
                                        collectionRow.remove();
                                    }, 500);
                                }
                            });
                            
                            // Also show notification in collections tab
                            showNotification('collection-notification', 'success', 'Collection dari buyer ini juga telah dihapus');
                        } else {
                            // Re-enable button if operation failed
                            button.disabled = false;
                            button.innerHTML = '<i class="fas fa-trash-alt"></i> Hapus';
                        }
                    };
                    
                    xhr.onerror = function() {
                        showNotification('buyer-notification', 'error', 'Gagal menghubungi server');
                        button.disabled = false;
                        button.innerHTML = '<i class="fas fa-trash-alt"></i> Hapus';
                    };
                    
                    xhr.send('action=delete_buyer&buyer_id=' + buyerId);
                }
            });
        });
    }
});
</script>

<?php include '../template_it/footer.php'; ?>