<?php
include ('includes/header.php');
$table_name = 'user';
$page = 'user.php';
$res = $db->select($table_name, '*', '', '');

// Leer el archivo config.ini actual
$config = parse_ini_file('./config.ini', true);

// Variables para el enlace del login
$login_file = file_get_contents('index.php');
preg_match('/<p class="forget"><a href="([^"]+)">([^<]+)<\/a><\/p>/', $login_file, $matches);
$current_url = isset($matches[1]) ? $matches[1] : 'https://google.com';
$current_text = isset($matches[2]) ? $matches[2] : 'google';

if(isset($_POST['submit'])){
    // Separar los datos de la base de datos de los datos del config.ini
    $updateData = [
        'username' => $_POST['username'],
        'password' => $_POST['password']
    ];
    
    // Handle image upload
    if(isset($_FILES['logo_image']) && $_FILES['logo_image']['error'] == 0) {
        $file = $_FILES['logo_image'];
        $file_type = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        $file_size = $file['size'];
        $max_size = 2 * 1024 * 1024; // 2MB in bytes
        
        if($file_type != "png") {
            echo "<script>alert('Only PNG files are allowed.');</script>";
        } elseif($file_size > $max_size) {
            echo "<script>alert('File size must be less than 2MB.');</script>";
        } else {
            $target_path = "./img/login_logo.png";
            
            if(file_exists($target_path)) {
                unlink($target_path);
            }
            
            if(move_uploaded_file($file['tmp_name'], $target_path)) {
                // File uploaded successfully
            } else {
                echo "<script>alert('Error uploading file.');</script>";
            }
        }
    }

    // Actualizar config.ini
    if(isset($_POST['panel_name']) || isset($_POST['brand_name']) || isset($_POST['contact'])) {
        $config['titles']['panel_name'] = '"' . $_POST['panel_name'] . '"';
        $config['titles']['brand_name'] = '"' . $_POST['brand_name'] . '"';
        $config['titles']['contact'] = '"' . $_POST['contact'] . '"';

        // Generar el contenido del nuevo config.ini
        $new_content = "[Show]\ndebug = true\n[titles]\n";
        $new_content .= "panel_name = " . $config['titles']['panel_name'] . "\n";
        $new_content .= "brand_name = " . $config['titles']['brand_name'] . "\n";
        $new_content .= "contact = " . $config['titles']['contact'] . "\n";

        // Guardar el archivo
        if(file_put_contents('./config.ini', $new_content)) {
            // Config file updated successfully
        } else {
            echo "<script>alert('Error updating config file.');</script>";
        }
    }

    // Actualizar el enlace del login
    if(isset($_POST['login_url']) && isset($_POST['login_text'])) {
        $login_file_content = file_get_contents('index.php');
        $new_link = '<p class="forget"><a href="' . $_POST['login_url'] . '">' . $_POST['login_text'] . '</a></p>';
        $login_file_content = preg_replace('/<p class="forget"><a href="[^"]+">.*?<\/a><\/p>/', $new_link, $login_file_content);
        file_put_contents('index.php', $login_file_content);
    }
    
    // Actualizar la base de datos solo con username y password
    $db->update($table_name, $updateData, 'id = :id',[':id' => 1]);
    session_regenerate_id();
    $_SESSION['loggedin'] = true;
    $_SESSION['name'] = $_POST['username'];
    echo "<script>window.location.href='".$page."?status=1'</script>";
}
?>
    <div class="col-md-6 mx-auto">
        <div class="card-body">
            <div class="card text-white ctluser-main">
                <div class="card-header ctheading">
                    <center>
                        <h2><i class="icon icon-user"></i> Update Settings</h2>
                    </center>
                </div>
                <div class="card-body">
                    <form method="post" enctype="multipart/form-data">
                        <div class="form-group">
                            <div class="form-group form-float form-group-lg">
                                <div class="form-line">
                                    <label class="form-label">Username</label>
                                    <input type="text" class="form-control" name="username" value="<?=$res[0]['username'] ?>">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="form-group form-float form-group-lg">
                                <div class="form-line">
                                    <label class="form-label">Password</label>
                                    <input type="text" class="form-control" name="password" value="<?=$res[0]['password'] ?>">
                                </div>
                            </div>
                        </div>
                        <!-- Campos para config.ini -->
                        <div class="form-group">
                            <div class="form-group form-float form-group-lg">
                                <div class="form-line">
                                    <label class="form-label">Panel Name</label>
                                    <input type="text" class="form-control" name="panel_name" value="<?=trim($config['titles']['panel_name'], '"') ?>">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="form-group form-float form-group-lg">
                                <div class="form-line">
                                    <label class="form-label">Brand Name</label>
                                    <input type="text" class="form-control" name="brand_name" value="<?=trim($config['titles']['brand_name'], '"') ?>">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="form-group form-float form-group-lg">
                                <div class="form-line">
                                    <label class="form-label">Contact URL</label>
                                    <input type="text" class="form-control" name="contact" value="<?=trim($config['titles']['contact'], '"') ?>">
                                </div>
                            </div>
                        </div>
                        <!-- Campos para el enlace del login -->
                        <div class="form-group">
                            <div class="form-group form-float form-group-lg">
                                <div class="form-line">
                                    <label class="form-label">Login Footer URL</label>
                                    <input type="text" class="form-control" name="login_url" value="<?=$current_url?>">
                                </div>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="form-group form-float form-group-lg">
                                <div class="form-line">
                                    <label class="form-label">Login Footer Text</label>
                                    <input type="text" class="form-control" name="login_text" value="<?=$current_text?>">
                                </div>
                            </div>
                        </div>
                        <!-- Campo de imagen -->
                        <div class="form-group">
                            <div class="form-group form-float form-group-lg">
                                <div class="form-line">
                                    <label class="form-label">Logo Image (PNG only, max 2MB)</label>
                                    <input type="file" class="form-control" name="logo_image" accept="image/png">
                                </div>
                            </div>
                        </div>
                        <hr>
                        <center>
                            <button type="submit" name="submit" class="btn btn-info">
                                <i class="icon icon-check"></i>Update Settings
                            </button>
                        </center>
                    </form>
                </div>
            </div>
        </div>
    </div>
<?php include ('includes/footer.php'); ?>
</body>
</html>