<?php
include('includes/header.php');

// Table name
$table_name = "playlist";

// Table call
$res = json_decode(file_get_contents('data.json'), true);

// Submit new
if (isset($_POST['submit'])) {
    unset($_POST['submit']); // Remove 'submit' from data sent to database
    $data = $_POST;
    $data['mac'] = uniqid(); // Generate a unique MAC address (or modify according to your logic)
    $res[] = $data; // Add data to array
    file_put_contents('data.json', json_encode($res)); // Save array to JSON
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=1'</script>";
}

// Update call
@$resU = $res[$_GET['update'] - 1]; // Assuming IDs are sequential

if (isset($_POST['submitU'])) {
    unset($_POST['submitU']); // Remove 'submitU' from data sent to database
    $updateData = $_POST;
    $updateData['mac'] = $resU['mac']; // Keep MAC address when updating
    $res[$_GET['update'] - 1] = $updateData; // Update data in array
    file_put_contents('data.json', json_encode($res)); // Save array to JSON
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=1'</script>";
}

// Delete row
if (isset($_GET['delete'])) {
    unset($res[$_GET['delete'] - 1]); // Remove element from array
    file_put_contents('data.json', json_encode(array_values($res))); // Reindex and save
    echo "<script>window.location.href='" . basename($_SERVER["SCRIPT_NAME"]) . "?status=2'</script>";
}
?>

<!-- Delete confirmation modal -->
<div class="modal fade" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h2>Confirm</h2>
            </div>
            <div class="modal-body">
                Do you really want to delete?
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <a class="btn btn-danger btn-ok">Delete</a>
            </div>
        </div>
    </div>
</div>

<?php if (isset($_GET['create'])) { ?>

<div class="col-md-8 mx-auto">
    <div class="card-body">
        <div class="card bg-primary text-white">
            <div class="card-header card-header-warning">
                <center>
                    <h2><i class="icon icon-bullhorn"></i> Add User</h2>
                </center>
            </div>
            <div class="card-body">
                <div class="col-12">
                    <h3>Add User</h3>
                </div>
                <form method="post">
                    <div class="form-group">
                        <label class="form-label" for="name">Name</label>
                        <input class="form-control" id="name" name="name" placeholder="Name" type="text" required />
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="username">Username</label>
                        <input class="form-control" id="username" name="username" placeholder="Username" type="text" required />
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="password">Password</label>
                        <input class="form-control" id="password" name="password" placeholder="Password" type="password" required />
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="expiration">Expiration</label>
                        <input class="form-control" id="expiration" name="expiration" placeholder="Expiration Date" type="date" required />
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="whatsapp">WhatsApp</label>
                        <input class="form-control" id="whatsapp" name="whatsapp" placeholder="WhatsApp Number" type="text" required />
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="email">Email</label>
                        <input class="form-control" id="email" name="email" placeholder="Email" type="email" required />
                    </div>
                    <div class="form-group">
                        <center>
                            <button class="btn btn-info" name="submit" type="submit">
                                <i class="icon icon-check"></i> Submit
                            </button>
                        </center>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php } else if (isset($_GET['update'])) { ?>

<div class="col-md-8 mx-auto">
    <div class="card-body">
        <div class="card bg-primary text-white">
            <div class="card-header card-header-warning">
                <center>
                    <h2><i class="icon icon-bullhorn"></i> Edit Current User</h2>
                </center>
            </div>
            <div class="card-body">
                <div class="col-12">
                    <h3>Edit User</h3>
                </div>
                <form method="post">
                    <div class="form-group">
                        <label class="form-label" for="name">Name</label>
                        <input class="form-control" id="name" name="name" value="<?= $resU['name'] ?>" placeholder="Name" type="text" required />
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="username">Username</label>
                        <input class="form-control" id="username" name="username" value="<?= $resU['username'] ?>" placeholder="Username" type="text" required />
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="password">Password</label>
                        <input class="form-control" id="password" name="password" value="<?= $resU['password'] ?>" placeholder="Password" type="password" required />
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="expiration">Expiration</label>
                        <input class="form-control" id="expiration" name="expiration" value="<?= $resU['expiration'] ?>" placeholder="Expiration Date" type="date" required />
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="whatsapp">WhatsApp</label>
                        <input class="form-control" id="whatsapp" name="whatsapp" value="<?= $resU['whatsapp'] ?>" placeholder="WhatsApp Number" type="text" required />
                    </div>
                    <div class="form-group">
                        <label class="form-label" for="email">Email</label>
                        <input class="form-control" id="email" name="email" value="<?= $resU['email'] ?>" placeholder="Email" type="email" required />
                    </div>
                    <div class="form-group">
                        <center>
                            <button class="btn btn-info" name="submitU" type="submit">
                                <i class="icon icon-check"></i> Submit
                            </button>
                        </center>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<?php } else { ?>

<div class="col-md-12 mx-auto">
    <div class="card-body">
        <div class="card bg-primary text-white">
            <div class="card-header card-header-warning">
                <center>
                    <h2><i class="icon icon-commenting"></i> Current Users</h2>
                </center>
            </div>
            <div class="card-body">
                <div class="col-12">
                    <center>
                        <a id="button" href="./<?= basename($_SERVER["SCRIPT_NAME"]) ?>?create" class="btn btn-info">Create User</a>
                    </center>
                </div>
                <br>
                <div class="table-responsive">
                    <input class="form-control" type="text" id="search" onkeyup="func2()" placeholder="Type to search">
                    <table id="users" class="table table-striped table-sm">
                        <thead style="color:white!important">
                            <tr class="header">
                                <th>Name</th>
                                <th>Username</th>
                                <th>Password</th>
                                <th>Expiration</th>
                                <th>WhatsApp</th>
                                <th>Email</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($res as $key => $user) { ?>
                            <tr>
                                <td><?= $user['name'] ?></td>
                                <td><?= $user['username'] ?></td>
                                <td><?= $user['password'] ?></td>
                                <td><?= $user['expiration'] ?></td>
                                <td>
                                    <?= $user['whatsapp'] ?>
                                    <a href="https://wa.me/<?= str_replace([' ', '-', '(', ')'], '', $user['whatsapp']) ?>?text=Hello <?= $user['name'] ?>, your subscription expires <?= $user['expiration'] ?>" class="btn btn-success btn-sm">
                                        Send Message
                                    </a>
                                </td>
                                <td><?= $user['email'] ?></td>
                                <td>
                                    <a href="?update=<?= $key + 1 ?>" class="btn btn-warning btn-sm">Edit</a>
                                    <button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#confirm-delete" data-href="?delete=<?= $key + 1 ?>">Delete</button>
                                </td>
                            </tr>
                            <?php } ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<?php } ?>

<script>
    function func2() {
        var input, filter, table, tr, td, i, j, txtValue;
        input = document.getElementById("search");
        filter = input.value.toUpperCase();
        table = document.getElementById("users");
        tr = table.getElementsByTagName("tr");
        
        for (i = 1; i < tr.length; i++) {
            tr[i].style.display = "none"; // Hide row
            td = tr[i].getElementsByTagName("td");
            for (j = 0; j < td.length; j++) {
                if (td[j]) {
                    txtValue = td[j].textContent || td[j].innerText;
                    if (txtValue.toUpperCase().indexOf(filter) > -1) {
                        tr[i].style.display = ""; // Show row
                        break;
                    }
                }
            }
        }
    }
</script>

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

<?php include('includes/footer.php'); ?>
