<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$db = new SQLite3('./api/.db.db');
$db->exec('CREATE TABLE IF NOT EXISTS ibo(id INTEGER PRIMARY KEY NOT NULL,mac_address VARCHAR(100),username VARCHAR(100),password VARCHAR(100),expire_date VARCHAR(100),url VARCHAR(100),title VARCHAR(100),created_at VARCHAR(100))');

if (isset($_GET['index'])) {
    $index = $_GET['index'];
} else {
    $index = "";
}

// Obtener DNS para el select
$dnsOptions = [];
$dnsResult = $db->query('SELECT * FROM dns');
while ($row = $dnsResult->fetchArray(SQLITE3_ASSOC)) {
    $dnsOptions[] = $row;
}

if (isset($_POST['submit'])) {
    $we = strtotime($_POST['expire_date']);
    $ne = date('Y-m-d', $we);
    $start = date('Y-m-d');
    $end = date('H:i:s');
    $full = $start . 'T' . $end . '.000000Z';

    $macAddresses = $_POST['mac_address'];

    foreach ($macAddresses as $mac) {
        $formattedMac = strtoupper($mac);
        $db->exec("INSERT INTO ibo(mac_address, username, password, expire_date, url, title, created_at)
                   VALUES('$formattedMac', '{$_POST['username']}', '{$_POST['password']}', '$ne', '{$_POST['dns']}', '{$_POST['title']}', '$full')");
    }

    $db->close();
    header('Location: users.php');
    exit;
}

$playlistNames = [
    'Ultimate Entertainment',
    'Global TV Hub',
    'Prime Streaming Zone',
    'All-in-One IPTV Lounge',
    'HD Channel Showcase',
    'Sports Mania',
    'Movie Magic',
    'News Network Central',
    'Kids Fun Zone',
    'Lifestyle Paradise',
    'Documentary Delight',
    'Music Melodies',
    'Comedy Central',
    'Reality TV Extravaganza',
    'Traveler\'s Guide',
    'Sci-Fi Spectacle',
    'Health and Fitness Channel',
    'Gaming Galaxy',
    'Fashion Forward',
    'Business Buzz',
    'Foodie Haven',
    'Educational Excellence',
    'Thriller Theater',
    'History Channel Vault',
    'Cartoons Unlimited',
    'Tech Titans',
    'Wildlife Adventure',
    'Artistic Expressions',
    'Supernatural Secrets',
    'Retro Rewind',
    'Romance Reels',
    'Spiritual Serenity',
    'DIY Network',
    'Car Enthusiast\'s Paradise',
    'Action Packed',
    'True Crime Stories',
    'International Flavor',
    'Nature\'s Wonders',
    'Home Makeover Madness',
    'Anime Haven',
    'Pop Culture Playground',
    'Hidden Gems',
    'Blockbuster Bonanza',
    'Motivational Mojo',
    'Vintage Vibes',
    'Outdoor Expeditions',
    'Social Media Stars',
    'Celebrity Showcase',
    'Science and Technology Marvels',
    'Fitness Freaks'
];

$randomPlaylistName = $playlistNames[array_rand($playlistNames)];

include 'includes/header.php';


?>

<script>
document.addEventListener("DOMContentLoaded", function() {
    function formatMacInput(input) {
        input.addEventListener("input", function(e) {
            var value = e.target.value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();
            var formatted = "";
            for (var i = 0; i < value.length; i++) {
                formatted += value[i];
                if ((i + 1) % 2 === 0 && i < value.length - 1) {
                    formatted += ":";
                }
            }
            e.target.value = formatted;
        });
    }

    formatMacInput(document.querySelector('.mac-input'));

    document.getElementById('add_mac_field').addEventListener('click', function () {
        var container = document.getElementById('mac_fields');
        var newInputGroup = document.createElement('div');
        newInputGroup.classList.add('input-group', 'mt-2');
        newInputGroup.innerHTML = `<input class="form-control text-primary mac-input" name="mac_address[]" type="text" placeholder="Enter MAC Address" required/>`;
        container.appendChild(newInputGroup);
        formatMacInput(newInputGroup.querySelector('.mac-input'));
    });
});
</script>
<div class="container-fluid">
    <h1 class="h3 mb-1 text-gray-800">Activate User</h1>
    <div class="card border-left-primary shadow h-100 card shadow mb-4">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold text-color"><i class="fas fa-user"></i> User Details</h6>
        </div>
        <div class="card-body">
            <form method="post">
                <div class="form-group">
                    <label><strong>Mac Address</strong></label>
                    <div id="mac_fields">
                        <div class="input-group">
                            <input class="form-control text-primary mac-input" name="mac_address[]" type="text" placeholder="Enter MAC Address" value="<?php echo strtoupper($index); ?>" required/>
                        </div>
                    </div>
                    <button type="button" id="add_mac_field" class="btn btn-secondary mt-2">Agregar otra MAC</button>
                </div>

                <div class="form-group">
                    <label><strong>Server Name</strong></label>
                    <input type="text" class="form-control text-primary" name="title" value="<?php echo $randomPlaylistName; ?>" required/>
                </div>

                <div class="form-group">
                    <label><strong>DNS</strong></label>
                    <select class="form-control text-primary" name="dns" required>
                        <option value="">Select DNS</option>
                        <?php foreach ($dnsOptions as $dns): ?>
                            <option value="<?php echo htmlspecialchars($dns['url']); ?>">
                                <?php echo htmlspecialchars($dns['url']); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="form-group">
                    <label><strong>Username</strong></label>
                    <input type="text" class="form-control text-primary" name="username" required/>
                </div>

                <div class="form-group">
                    <label><strong>Password</strong></label>
                    <input type="text" class="form-control text-primary" name="password" required/>
                </div>

                <div class="form-group">
                    <label><strong>Expiration</strong></label>
                    <input type="text" placeholder="YYYY-MM-DD" class="form-control text-primary" name="expire_date" id="datetimepicker"/>
                </div>

                <button type="submit" name="submit" class="btn btn-success btn-icon-split">
                    <span class="icon text-white-50"><i class="fas fa-check"></i></span>
                    <span class="text">Submit</span>
                    </button>
                </div>
            </div>
</form>
</div>
</div>
</div>
<br><br><br>

<script>
$('#confirm-delete').on('show.bs.modal', function(e) {
    $(this).find('.btn-ok').attr('href', $(e.relatedTarget).data('href'));
});
</script>


</body>
<?php 
include 'includes/footer.php';
?>
</html>