<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Connect to the SQLite database
$db = new SQLite3('./api/.db.db');

// Retrieve user data based on the 'update' parameter from the URL
$updateId = $_GET['update'];

// Fetch data from the 'ibo' table
$res = $db->query('SELECT * FROM ibo WHERE id=\'' . $updateId . '\'');
$row = $res->fetchArray();

$id = $row['id'];
$mac_address = $row['mac_address'];
$expire_date = $row['expire_date'];
$username = $row['username'];
$password = $row['password'];
$url = $row['url'];
$title = $row['title'];

// Check if the form has been submitted
if (isset($_POST['submit'])) {
    // Format the expiration date
    $we = strtotime($_POST['expire_date']);
    $ne = date('Y-m-d', $we);
    $start = date('Y-m-d');
    $end = date('h:m:s');
    $full = $start . 'T' . $end . '.000000Z';

    // Update the 'ibo' table with the new data
    $db->exec('UPDATE ibo SET 
        mac_address=\'' . $_POST['mac_address'] . '\',
        expire_date=\'' . $ne . '\',
        username=\'' . $_POST['username'] . '\',
        url=\'' . $_POST['url'] . '\',
        title=\'' . $_POST['title'] . '\',
        password=\'' . $_POST['password'] . '\',
        created_at=\'' . $full . '\'
        WHERE id=\'' . $_POST['id'] . '\''
    );

    // Update the 'subscription' table with the same MAC address and expiration date
    $expireDateTimestamp = strtotime($_POST['expire_date']);
    $formattedExpireDate = date('Y-m-d', $expireDateTimestamp);

    // Update subscription table to reflect the new mac_address and expire_date
    $updateQuery = 'UPDATE subscription SET 
        mac_address=:mac_address, 
        expire_date=:expire_date 
        WHERE mac_address=:mac_address';
    $updateStmt = $db->prepare($updateQuery);
    $updateStmt->bindValue(':mac_address', $_POST['mac_address'], SQLITE3_TEXT);
    $updateStmt->bindValue(':expire_date', $formattedExpireDate, SQLITE3_TEXT);
    $updateStmt->execute();

    // Close the database connection and redirect
    $db->close();
    header('Location: users.php');
}

// Include the header
include 'includes/header.php';

// Store user data in variables for use in the HTML form
$userUpdateId = $row['id'];
$userUpdateMacAddress = $row['mac_address'];
$userUpdateExpireDate = $row['expire_date'];
$userUpdateUsername = $row['username'];
$userUpdatePassword = $row['password'];
$userUpdateUrl = $row['url'];
$userUpdateTitle = $row['title'];

?>

<!-- Display the form with user data -->
<div class="container-fluid">
    <div class="mx-auto" style="max-width: 900px;">
        <h1 class="title-outside-card mb-1">Actualizar Usuario</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="fa fa-user"></i> Editar Usuario</h6>
            </div>
            <div class="card-body">
                <form method="post">
                    <div class="form-group">
                        <label class="control-label" for="mac_address"><strong>Mac Address</strong></label>
                        <div class="input-group">
                            <input type="hidden" name="id" value="<?= $id ?>" />
                            <input class="form-control text-primary" id="description" name="mac_address" value="<?= $mac_address ?>" type="text" required />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="username"><strong>Usuario</strong></label>
                        <div class="input-group">
                            <input type="text" class="form-control text-primary" name="username" value="<?= $username ?>" id="description" required />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="password"><strong>Contraseña</strong></label>
                        <div class="input-group">
                            <input type="text" class="form-control text-primary" name="password" value="<?= $password ?>" id="description" required />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="expire_date"><strong>Fecha de Expiración</strong></label>
                        <div class="input-group">
                            <input type="text" class="form-control text-primary" name="expire_date" value="<?= $expire_date ?>" id="datepicker" />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="url"><strong>URL</strong></label>
                        <div class="input-group">
                            <input type="text" class="form-control text-primary" name="url" value="<?= $url ?>" id="description" required />
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="control-label" for="title"><strong>Título</strong></label>
                        <div class="input-group">
                            <input type="text" class="form-control text-primary" name="title" value="<?= $title ?>" id="description" required />
                        </div>
                    </div>
                    <div class="form-group">
                        <div>
                            <button class="btn btn-success btn-icon-split" name="submit" type="submit">
                                <span class="icon text-white-50"><i class="fa fa-check"></i></span><span class="text">Guardar</span>
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
