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

include(__DIR__ . '/includes/functions.php');
$static_url = dirname($_SERVER['SCRIPT_NAME']) . '/assets/';
include 'session_check.php';

// Configurações do arquivo 📁
$configFile = __DIR__ . '/api/config.json';
$configData = ['show_all_apps_button' => true];

// Carrega configurações existentes 📤
if (file_exists($configFile)) {
    $configContent = file_get_contents($configFile);
    $configData = json_decode($configContent, true);
}

// Processamento do formulário 📝
$success_message = "";
$error_message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Atualizar configuração ⚙️
    $newValue = isset($_POST['show_all_apps_button']) ? true : false;
    $configData['show_all_apps_button'] = $newValue;
    
    // Salvar no arquivo JSON 💾
    if (file_put_contents($configFile, json_encode($configData, JSON_PRETTY_PRINT))) {
        $success_message = $newValue ? 
            "✅ Botão ativado com sucesso! Os clientes agora podem ver todos os aplicativos." : 
            "✅ Botão desativado com sucesso! O menu de apps originais será ocultado.";
    } else {
        $error_message = "❌ Erro ao salvar configuração. Verifique as permissões do arquivo.";
    }
}

$page_title = "📱 Gestisci pulsante app";

$page_content = '<div class="container mt-5">
    <div class="card mb-5 mb-xl-12">
        <div class="card-body py-12">
            <div class="d-flex align-items-center mb-7">
                <span class="symbol symbol-50px me-5">
                    <span class="symbol-label bg-light-primary">
                        <i class="ki-outline ki-abstract-26 fs-2x text-primary"></i>
                    </span>
                </span>
                <div>
                    <h2 class="mb-1">📲 Controlla il pulsante "Mostra tutte le app"</h2>
                    <p class="text-gray-600">Gestire la visibilità del menu dell applicazione nativa</p>
                </div>
            </div>';

if (!empty($success_message)) {
    $page_content .= '<div class="alert alert-success d-flex align-items-center" role="alert">
        <i class="ki-outline ki-check-circle fs-2x text-success me-4"></i>
        <div class="d-flex flex-column">
            <h4 class="mb-1 text-success">Sucesso!</h4>
            <span>' . htmlspecialchars($success_message) . '</span>
        </div>
    </div>';
}

if (!empty($error_message)) {
    $page_content .= '<div class="alert alert-danger d-flex align-items-center" role="alert">
        <i class="ki-outline ki-cross-circle fs-2x text-danger me-4"></i>
        <div class="d-flex flex-column">
            <h4 class="mb-1 text-danger">Erro!</h4>
            <span>' . htmlspecialchars($error_message) . '</span>
        </div>
    </div>';
}

$page_content .= '<form method="POST" action="">
    <div class="row g-6 mb-10">
        <div class="col-xl-12">
            <div class="card card-flush">
                <div class="card-header">
                    <h3 class="card-title">⚙️Configurazione dei pulsanti</h3>
                </div>
                <div class="card-body pt-1">
                    <div class="form-check form-switch form-check-custom form-check-solid mb-5">
                        <input class="form-check-input" type="checkbox" 
                            id="show_all_apps_button" name="show_all_apps_button" 
                            ' . ($configData['show_all_apps_button'] ? 'checked' : '') . '>
                        <label class="form-check-label" for="show_all_apps_button">
                            <strong>Mostra il pulsante "Tutte le applicazioni"</strong>
                        </label>
                    </div>
                    
                    <div class="notice d-flex bg-light-info rounded border-info border border-dashed p-6">
                        <i class="ki-outline ki-information-5 fs-2x text-info me-4"></i>
                        <div class="d-flex flex-stack flex-grow-1">
                            <div class="fw-semibold">
                                <h4 class="text-gray-900 fw-bold">ℹ️ Come funziona</h4>
                                <div class="fs-6 text-gray-700">
                                    <p>Quando <strong>ativado</strong>:</p>
                                    <ul>
                                        <li>👁️I clienti vedranno un pulsante per visualizzare tutte le app installate</li>
                                        <li>📋 L elenco include le app di avvio originali da launcher</li>
                                        <li>🔍Consente la navigazione completa sul dispositivo</li>
                                    </ul>
                                    <p>Quando <strong>desativado</strong>:</p>
                                    <ul>
                                        <li>🚫 Il pulsante sarà nascosto dall interfaccia</li>
                                        <li>📱 Saranno visibili solo le app consentite</li>
                                        <li>🔒 Esperienza più controllata</li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="d-flex justify-content-between mt-8">
        <button type="submit" class="btn btn-primary btn-lg">
            <i class="ki-outline ki-check fs-2 me-2"></i> 💾 Salva configurazione
        </button>
        
        <a href="javascript:history.back()" class="btn btn-secondary btn-lg">
            <i class="ki-outline ki-arrow-left fs-2 me-2"></i> Per tornare indietro
        </a>
    </div>
</form>

<div class="separator separator-dashed my-10"></div>

<div class="row">
    <div class="col-xl-12">
        <h4 class="mb-4">📋 Stato attuale</h4>
        <div class="card card-flush">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="symbol symbol-50px me-5">
                        <span class="symbol-label bg-light-' . ($configData['show_all_apps_button'] ? 'success' : 'danger') . '">
                            <i class="ki-outline ki-' . ($configData['show_all_apps_button'] ? 'check' : 'cross') . ' fs-2x text-' . ($configData['show_all_apps_button'] ? 'success' : 'danger') . '"></i>
                        </span>
                    </div>
                    <div class="flex-grow-1">
                        <h3 class="text-gray-800 fw-bold">Il pulsante è attualmente: ' . 
                        ($configData['show_all_apps_button'] ? 
                            '<span class="text-success">ATTIVATO ✅</span>' : 
                            '<span class="text-danger">DISABILI ❌</span>') . 
                        '</h3>
                        <p class="text-gray-600">Ultima modifica: ' . date('d/m/Y H:i:s') . '</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>';

include 'includes/layout.php';
?>