<?php
session_start();
include '../db_config.php';
include '../functions.php';

check_login();
check_role('admin');

$msg = '';
$error = '';

// Auto-fix: Create table if not exists
$conn->query("CREATE TABLE IF NOT EXISTS `dme_details` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `full_name` varchar(255) NOT NULL,
  `nic` varchar(20) NOT NULL,
  `district` varchar(100) NOT NULL,
  `divisional_secretariat` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  FOREIGN KEY (`user_id`) REFERENCES `dme_login`(`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");

if(isset($_POST['add'])) {
    // Arrays
    $emails = $_POST['email'];
    $full_names = $_POST['full_name'];
    $nics = $_POST['nic'];
    $districts = $_POST['district'];
    $ds_divs = $_POST['ds_div'];
    $passwords = $_POST['password'];

    $count = count($emails);
    $added = 0;
    $errors_list = [];

    for($i = 0; $i < $count; $i++) {
        $e = sanitize_input($emails[$i]);
        if(empty($e)) continue;

        // Simple check for duplicate email
        $check = $conn->query("SELECT id FROM dme_login WHERE username='$e'");
        if($check->num_rows > 0) {
            $errors_list[] = "Email $e already exists.";
        } else {
            $p = password_hash($passwords[$i], PASSWORD_DEFAULT);
            $full_name = sanitize_input($full_names[$i]);
            $nic = sanitize_input($nics[$i]);
            $district = sanitize_input($districts[$i]);
            $ds_div = sanitize_input($ds_divs[$i]);

            if($conn->query("INSERT INTO dme_login (username, password, role) VALUES ('$e', '$p', 'dme')")) {
                $dme_id = $conn->insert_id;
                $conn->query("INSERT INTO dme_details (user_id, full_name, nic, district, divisional_secretariat) VALUES ($dme_id, '$full_name', '$nic', '$district', '$ds_div')");
                $added++;
            } else {
                 $errors_list[] = "Error adding $e: " . $conn->error;
            }
        }
    }

    if($added > 0) {
        $msg = "Successfully added $added new DME Officer(s).";
    }
    if(!empty($errors_list)) {
        $error = implode("<br>", $errors_list);
    }
}

// CSV Upload Handler
if(isset($_POST['upload_csv']) && isset($_FILES['csv_file'])) {
    $file = $_FILES['csv_file']['tmp_name'];
    $handle = fopen($file, "r");
    
    if($handle) {
        // Skip header row
        fgetcsv($handle, 1000, ",");
        
        $added = 0;
        $errors_list = [];
        $row_num = 1;

        while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $row_num++;
            // Expected format: Name, NIC, District, DS, Email, Password
            if(count($data) < 6) {
                $errors_list[] = "Row $row_num: Invalid format.";
                continue;
            }

            $full_name = sanitize_input($data[0]);
            $nic = sanitize_input($data[1]);
            $district = sanitize_input($data[2]);
            $ds_div = sanitize_input($data[3]);
            $email = sanitize_input($data[4]);
            $password = $data[5];

            if(empty($email) || empty($password)) continue;

             // Simple check for duplicate email
            $check = $conn->query("SELECT id FROM dme_login WHERE username='$email'");
            if($check->num_rows > 0) {
                $errors_list[] = "Row $row_num: Email $email already exists.";
            } else {
                $p = password_hash($password, PASSWORD_DEFAULT);
                if($conn->query("INSERT INTO dme_login (username, password, role) VALUES ('$email', '$p', 'dme')")) {
                    $dme_id = $conn->insert_id;
                    $conn->query("INSERT INTO dme_details (user_id, full_name, nic, district, divisional_secretariat) VALUES ($dme_id, '$full_name', '$nic', '$district', '$ds_div')");
                    $added++;
                } else {
                     $errors_list[] = "Row $row_num: Error adding $email: " . $conn->error;
                }
            }
        }
        fclose($handle);

        if($added > 0) {
            $msg = "CSV Import Successful. Added $added officers.";
        }
        if(!empty($errors_list)) {
            $error = "Import Errors:<br>" . implode("<br>", $errors_list);
        }

    } else {
        $error = "Error opening CSV file.";
    }
}

if(isset($_POST['update_email'])) {
    $id = intval($_POST['id']);
    $email = sanitize_input($_POST['email']);
    $stmt = $conn->prepare("UPDATE dme_login SET username=? WHERE id=?");
    $stmt->bind_param("si", $email, $id);
    $stmt->execute();
    $stmt->close();
    $msg = "DME email updated successfully.";
}

if(isset($_POST['reset_password'])) {
    $id = intval($_POST['id']);
    $pass = password_hash($_POST['new_password'], PASSWORD_DEFAULT);
    $stmt = $conn->prepare("UPDATE dme_login SET password=? WHERE id=?");
    $stmt->bind_param("si", $pass, $id);
    $stmt->execute();
    $stmt->close();
    $msg = "DME password reset successfully.";
}

if(isset($_GET['del'])) {
    $del_id = intval($_GET['del']);
    
    $stmt1 = $conn->prepare("DELETE FROM dme_login WHERE id=?");
    $stmt1->bind_param("i", $del_id);
    $stmt1->execute();
    $stmt1->close();
    
    $stmt2 = $conn->prepare("DELETE FROM dme_details WHERE user_id=?");
    $stmt2->bind_param("i", $del_id);
    $stmt2->execute();
    $stmt2->close();
    
    $msg = "DME Officer account deleted.";
}

$res = $conn->query("SELECT u.*, d.full_name, d.nic, d.district, d.divisional_secretariat FROM dme_login u LEFT JOIN dme_details d ON u.id=d.user_id WHERE u.role='dme'");
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage DMEs | Admin Panel</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <script src="https://unpkg.com/lucide@latest"></script>
    <style> 
        body { font-family: 'Inter', sans-serif; } 
        .glass-panel {
            background: rgba(30, 41, 59, 0.4);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        /* Custom scrollbar for better look in dark mode */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #1e293b; 
        }
        ::-webkit-scrollbar-thumb {
            background: #475569; 
            border-radius: 4px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #64748b; 
        }
    </style>
</head>
<body class="bg-slate-950 min-h-screen text-slate-200 selection:bg-indigo-500 selection:text-white">

    <!-- Navbar -->
    <nav class="bg-slate-900 border-b border-slate-800 sticky top-0 z-50">
        <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
            <div class="flex justify-between h-20 items-center">
                <a href="<?= BASE_URL ?>/index.php" class="text-2xl font-bold italic tracking-tighter text-white">
                    Work For <span class="text-indigo-400">Sri Lanka</span>
                    <span class="text-xs font-normal text-white bg-indigo-600 px-2 py-0.5 rounded ml-2 align-middle border border-indigo-500/50">Admin Panel</span>
                </a>
                <div class="flex items-center gap-6">
                    <span class="text-sm font-medium text-slate-400 hidden md:inline">Logged in as: <span class="text-indigo-400 font-mono"><?=$_SESSION['username']?></span></span>
                    <a href="../logout.php" class="text-slate-400 hover:text-red-400 font-medium transition text-sm flex items-center">
                        <i data-lucide="log-out" class="w-4 h-4 mr-2"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </nav>

    <!-- Header Section -->
    <div class="relative bg-slate-900 py-10 px-4 border-b border-slate-800">
        <div class="absolute top-0 right-0 w-[500px] h-[500px] bg-indigo-600/10 rounded-full blur-[100px] -mt-20 -mr-20 pointer-events-none"></div>
        
        <div class="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center gap-4 relative z-10">
            <div>
                <h1 class="text-3xl font-bold mb-2 text-white">Manage DME Officers</h1>
                <p class="text-slate-400">Create and manage accounts for Divisional Management Executives.</p>
            </div>
             <a href="dashboard.php" class="bg-slate-800 hover:bg-slate-700 text-white px-5 py-2.5 rounded-xl font-bold transition flex items-center border border-slate-700 hover:border-indigo-500 hover:text-indigo-400 shadow-sm text-sm group">
                <i data-lucide="arrow-left" class="w-4 h-4 mr-2 group-hover:-translate-x-1 transition-transform"></i> Back to Dashboard
            </a>
        </div>
    </div>

    <!-- Main Content -->
    <div class="max-w-7xl mx-auto px-4 pb-20 pt-8">
        
        <?php if($msg): ?>
            <div class="bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 px-6 py-4 rounded-xl mb-6 flex items-center shadow-sm animate-fade-in-down">
                <i data-lucide="check-circle" class="w-5 h-5 mr-3 flex-shrink-0"></i>
                <span class="font-bold mr-2">Success!</span> <?=$msg?>
            </div>
        <?php endif; ?>

        <?php if($error): ?>
            <div class="bg-red-500/10 border border-red-500/20 text-red-400 px-6 py-4 rounded-xl mb-6 flex items-center shadow-sm animate-pulse">
                <i data-lucide="alert-circle" class="w-5 h-5 mr-3 flex-shrink-0"></i>
                <div><?=$error?></div>
            </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            
            <!-- Add New Form -->
            <div class="lg:col-span-1">
                <div class="glass-panel rounded-3xl shadow-xl overflow-hidden sticky top-24">
                    <div class="p-6 border-b border-slate-700/50 bg-slate-800/30">
                        <h2 class="text-lg font-bold text-white flex items-center">
                            <i data-lucide="user-plus" class="w-5 h-5 mr-2 text-indigo-400"></i> Register New Officer
                        </h2>
                    </div>
                    
                    <!-- Tabs for Single/Bulk -->
                    <div class="px-6 pt-4 flex gap-4 border-b border-slate-700/50 bg-slate-800/20" id="regTabs">
                        <button onclick="switchTab('single')" class="pb-2 text-sm font-bold text-indigo-400 border-b-2 border-indigo-500 transition-colors" id="tab-single">Manual Entry</button>
                        <button onclick="switchTab('csv')" class="pb-2 text-sm font-bold text-slate-500 hover:text-indigo-400 border-b-2 border-transparent transition-colors" id="tab-csv">Upload CSV</button>
                    </div>

                    <!-- CSV Upload Form -->
                    <form method="post" enctype="multipart/form-data" class="p-6 space-y-4 hidden" id="csvForm">
                        <input type="hidden" name="upload_csv" value="1">
                        
                        <div class="bg-indigo-500/10 border border-indigo-500/20 rounded-xl p-4 text-sm text-indigo-300 mb-2">
                            <p class="font-bold mb-1 text-white">Bulk Registration Instructions:</p>
                            <ul class="list-disc pl-4 space-y-1 text-xs text-indigo-200/80">
                                <li>Upload a CSV file with headers: <code>Full Name, NIC, District, Divisional Secretariat, Email, Password</code></li>
                                <li>Ensure emails are unique.</li>
                                <li><a href="dme_template.csv" download class="underline font-bold hover:text-white transition-colors">Download Template CSV</a></li>
                            </ul>
                        </div>

                        <div>
                            <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">Select CSV File</label>
                            <input type="file" name="csv_file" accept=".csv" required class="w-full px-4 py-2 bg-slate-900/50 border border-slate-700 rounded-xl text-sm file:mr-4 file:py-2 file:px-4 file:rounded-lg file:border-0 file:text-xs file:font-bold file:bg-indigo-600 file:text-white hover:file:bg-indigo-500 text-slate-300 transition cursor-pointer">
                        </div>

                        <button type="submit" class="w-full bg-indigo-600 hover:bg-indigo-500 text-white font-bold py-3 rounded-xl shadow-lg shadow-indigo-600/20 hover:shadow-indigo-600/40 transition transform active:scale-95 flex items-center justify-center">
                            <i data-lucide="upload" class="w-4 h-4 mr-2"></i> Upload & Register
                        </button>
                    </form>

                    <!-- Manual Entry Form -->
                    <form method="post" class="p-6 space-y-4" id="manualForm">
                        <input type="hidden" name="add" value="1">
                        
                        <div id="dme-forms-container" class="space-y-6">
                            <!-- Initial Form Row -->
                            <div class="dme-row border-b border-slate-700/50 pb-6 relative">
                                <div class="grid grid-cols-1 gap-4">
                                    <div>
                                        <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">Full Name</label>
                                        <input type="text" name="full_name[]" required class="w-full px-4 py-2 bg-slate-900/50 border border-slate-700 rounded-xl text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition outline-none text-white placeholder-slate-600" placeholder="Officer Name">
                                    </div>
                                    <div>
                                        <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">NIC Number</label>
                                        <input type="text" name="nic[]" required class="w-full px-4 py-2 bg-slate-900/50 border border-slate-700 rounded-xl text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition outline-none text-white placeholder-slate-600" placeholder="National ID">
                                    </div>
                                    <div class="grid grid-cols-2 gap-4">
                                        <div>
                                            <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">District</label>
                                            <select name="district[]" required class="w-full px-4 py-2 bg-slate-900/50 border border-slate-700 rounded-xl text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition outline-none text-white">
                                                <option value="" class="bg-slate-900">Select District</option>
                                                <?php
                                                include_once '../districts.php';
                                                $districts = get_districts();
                                                if(!empty($districts)) {
                                                    foreach(array_keys($districts) as $d) {
                                                        echo "<option value='$d' class='bg-slate-900'>$d</option>";
                                                    }
                                                }
                                                ?>
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">Div. Sec.</label>
                                            <input type="text" name="ds_div[]" required class="w-full px-4 py-2 bg-slate-900/50 border border-slate-700 rounded-xl text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition outline-none text-white placeholder-slate-600" placeholder="DS Name">
                                        </div>
                                    </div>
                                    <div>
                                        <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">Email / Username</label>
                                        <input type="email" name="email[]" required class="w-full px-4 py-2 bg-slate-900/50 border border-slate-700 rounded-xl text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition outline-none text-white placeholder-slate-600" placeholder="dme@workforsl.com">
                                    </div>
                                    <div>
                                        <label class="block text-xs font-bold text-slate-400 uppercase tracking-wide mb-1">Password</label>
                                        <input type="text" name="password[]" required class="w-full px-4 py-2 bg-slate-900/50 border border-slate-700 rounded-xl text-sm focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition outline-none text-white placeholder-slate-600" placeholder="Assign password">
                                    </div>
                                </div>
                                <button type="button" onclick="removeRow(this)" class="absolute top-0 right-0 p-1 text-red-500 hover:text-red-400 transition hidden remove-btn bg-slate-800 rounded-full border border-slate-700" title="Remove Row">
                                    <i data-lucide="x" class="w-4 h-4"></i>
                                </button>
                            </div>
                        </div>

                        <div class="flex gap-2 pt-2">
                             <button type="button" onclick="addMore()" class="flex-1 bg-slate-800 hover:bg-slate-700 text-slate-400 hover:text-white font-bold py-3 rounded-xl transition flex items-center justify-center border border-slate-700 border-dashed hover:border-indigo-500/50">
                                <i data-lucide="plus" class="w-4 h-4 mr-2"></i> Add Another
                            </button>
                            <button type="submit" class="flex-1 bg-indigo-600 hover:bg-indigo-500 text-white font-bold py-3 rounded-xl shadow-lg shadow-indigo-600/20 hover:shadow-indigo-600/40 transition transform active:scale-95 flex items-center justify-center">
                                Create Accounts
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- List of DMEs -->
            <div class="lg:col-span-2">
                <div class="glass-panel rounded-3xl shadow-xl overflow-hidden">
                    <div class="p-6 border-b border-slate-700/50 bg-slate-800/30 flex justify-between items-center flex-wrap gap-4">
                        <h2 class="text-lg font-bold text-white flex items-center">
                            <i data-lucide="users" class="w-5 h-5 mr-2 text-indigo-400"></i> Active Officers
                        </h2>
                        <span class="bg-indigo-500/10 text-indigo-400 text-xs font-bold px-3 py-1 rounded-full border border-indigo-500/20"><?=$res->num_rows?> Active</span>
                    </div>
                     <div class="px-6 pb-4 pt-4 bg-slate-800/10 border-b border-slate-700/50">
                        <div class="relative">
                             <span class="absolute left-3 top-2.5 text-slate-500"><i data-lucide="search" class="w-4 h-4"></i></span>
                             <input type="text" id="searchInput" onkeyup="searchTable()" placeholder="Search by NIC, Name, District..." class="w-full pl-10 pr-4 py-2 bg-slate-900/50 border border-slate-700 rounded-xl text-sm focus:outline-none focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 transition shadow-sm text-white placeholder-slate-600">
                        </div>
                    </div>

                    <div class="overflow-x-auto max-h-[800px]">
                        <?php if($res->num_rows > 0): ?>
                        <table class="w-full text-left text-sm text-slate-400">
                            <thead class="bg-slate-800/50 text-slate-400 uppercase font-semibold text-xs tracking-wider sticky top-0 z-10 backdrop-blur-md">
                                <tr>
                                    <th class="px-6 py-4">ID</th>
                                    <th class="px-6 py-4">Officer Details</th>
                                    <th class="px-6 py-4">District / Div. Sec</th>
                                    <th class="px-6 py-4 text-right">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-slate-700/50">
                                <?php while($r = $res->fetch_assoc()): ?>
                                <tr class="hover:bg-slate-800/30 transition group">
                                    <td class="px-6 py-4 font-mono text-slate-600">#<?=$r['id']?></td>
                                    <td class="px-6 py-4">
                                        <div class="font-bold text-white"><?=$r['full_name'] ? $r['full_name'] : 'N/A'?></div>
                                        <div class="text-xs text-indigo-400/80"><?=$r['username']?></div>
                                        <div class="text-xs text-slate-500 font-mono mt-0.5"><?=$r['nic'] ? 'NIC: '.$r['nic'] : ''?></div>
                                    </td>
                                    <td class="px-6 py-4">
                                        <div class="font-medium text-slate-300"><?=$r['district'] ? $r['district'] : 'N/A'?></div>
                                        <div class="text-xs text-slate-500"><?=$r['divisional_secretariat'] ? $r['divisional_secretariat'] : ''?></div>
                                    </td>
                                    <td class="px-6 py-4 text-right">
                                        <div class="flex items-center justify-end gap-2 opacity-60 group-hover:opacity-100 transition-opacity">
                                            <button onclick="editDme(<?=$r['id']?>, '<?=$r['username']?>')" class="bg-indigo-500/10 hover:bg-indigo-500/20 text-indigo-400 p-2 rounded-lg transition border border-indigo-500/20" title="Edit Email">
                                                <i data-lucide="edit-2" class="w-4 h-4"></i>
                                            </button>
                                            <button onclick="resetPass(<?=$r['id']?>, '<?=$r['username']?>')" class="bg-yellow-500/10 hover:bg-yellow-500/20 text-yellow-400 p-2 rounded-lg transition border border-yellow-500/20" title="Reset Password">
                                                <i data-lucide="key" class="w-4 h-4"></i>
                                            </button>
                                            <a href="?del=<?=$r['id']?>" onclick="return confirm('Are you sure you want to delete this account?');" class="bg-red-500/10 hover:bg-red-500/20 text-red-400 p-2 rounded-lg transition border border-red-500/20" title="Delete">
                                                <i data-lucide="trash-2" class="w-4 h-4"></i>
                                            </a>
                                        </div>
                                    </td>
                                </tr>
                                <?php endwhile; ?>
                            </tbody>
                        </table>
                        <?php else: ?>
                            <div class="p-12 text-center text-slate-500 flex flex-col items-center">
                                <div class="bg-slate-800 p-4 rounded-full mb-3 border border-slate-700">
                                    <i data-lucide="users" class="w-8 h-8 text-slate-600"></i>
                                </div>
                                <p>No DME officers found.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Hidden Form for Edit -->
    <form id="editForm" method="post" style="display:none;">
        <input type="hidden" name="update_email" value="1">
        <input type="hidden" name="id" id="editId">
        <input type="hidden" name="email" id="editEmail">
    </form>
    
    <form id="resetForm" method="post" style="display:none;">
        <input type="hidden" name="reset_password" value="1">
        <input type="hidden" name="id" id="resetId">
        <input type="hidden" name="new_password" id="resetPassInput">
    </form>

    <!-- Simple Footer -->
    <footer class="bg-slate-900 border-t border-slate-800 py-8 text-center text-slate-500 text-sm mt-12">
        <p>&copy; <?=date('Y')?> Work For Sri Lanka. All rights reserved.</p>
    </footer>

    <script>
        lucide.createIcons();
        
        function editDme(id, currentEmail) {
            let newEmail = prompt("Enter new email address:", currentEmail);
            if(newEmail != null && newEmail != "") {
                document.getElementById('editId').value = id;
                document.getElementById('editEmail').value = newEmail;
                document.getElementById('editForm').submit();
            }
        }
        function resetPass(id, name) {
            let newPass = prompt("Enter NEW PASSWORD for " + name + ":");
            if(newPass != null && newPass != "") {
                document.getElementById('resetId').value = id;
                document.getElementById('resetPassInput').value = newPass;
                document.getElementById('resetForm').submit();
            }
        }

        function searchTable() {
            var input, filter, table, tr, td, i, txtValue;
            input = document.getElementById("searchInput");
            filter = input.value.toUpperCase();
            table = document.querySelector("table");
            if(!table) return;
            tr = table.getElementsByTagName("tr");
            for (i = 0; i < tr.length; i++) {
                // Skip header row
                if(tr[i].getElementsByTagName("th").length > 0) continue;
                
                // Get all text content from the row
                var rowContent = tr[i].textContent || tr[i].innerText;
                
                if (rowContent.toUpperCase().indexOf(filter) > -1) {
                    tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }

        function addMore() {
            const container = document.getElementById('dme-forms-container');
            const firstRow = container.querySelector('.dme-row');
            const newRow = firstRow.cloneNode(true);
            
            // Clear inputs
            const inputs = newRow.querySelectorAll('input');
            inputs.forEach(input => input.value = '');
            
            // Show remove button
            const removeBtn = newRow.querySelector('.remove-btn');
            removeBtn.classList.remove('hidden');
            
            container.appendChild(newRow);
            lucide.createIcons();
        }

        function removeRow(btn) {
            const row = btn.closest('.dme-row');
            if(document.querySelectorAll('.dme-row').length > 1) {
                row.remove();
            }
        }

        function switchTab(tab) {
            const manualForm = document.getElementById('manualForm');
            const csvForm = document.getElementById('csvForm');
            const tabSingle = document.getElementById('tab-single');
            const tabCsv = document.getElementById('tab-csv');

            if(tab === 'single') {
                manualForm.classList.remove('hidden');
                csvForm.classList.add('hidden');
                
                tabSingle.classList.add('text-indigo-400', 'border-indigo-500');
                tabSingle.classList.remove('text-slate-500', 'border-transparent');
                
                tabCsv.classList.remove('text-indigo-400', 'border-indigo-500');
                tabCsv.classList.add('text-slate-500', 'border-transparent');
            } else {
                manualForm.classList.add('hidden');
                csvForm.classList.remove('hidden');

                tabCsv.classList.add('text-indigo-400', 'border-indigo-500');
                tabCsv.classList.remove('text-slate-500', 'border-transparent');
                
                tabSingle.classList.remove('text-indigo-400', 'border-indigo-500');
                tabSingle.classList.add('text-slate-500', 'border-transparent');
            }
        }
    </script>
</body>
</html>
