<?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 = [
    'pin_enabled' => false,
    'pin_value' => '1234'
];

// Carrega configurações existentes 📤
if (file_exists($configFile)) {
    $configContent = file_get_contents($configFile);
    $loadedData = json_decode($configContent, true);
    if (is_array($loadedData)) {
        $configData = array_merge($configData, $loadedData); // garante que chaves padrão existam
    }
}

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

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    try {
        $pinEnabled = isset($_POST['pin_enabled']) ? true : false;
        $pinValue = isset($_POST['pin_value']) ? trim($_POST['pin_value']) : '';

        // Validação do PIN
        if ($pinEnabled) {
            if (empty($pinValue)) {
                throw new Exception("⚠️ Inserisci un PIN valido");
            }

            if (!preg_match('/^\d{4,6}$/', $pinValue)) {
                throw new Exception("⚠️ Il PIN deve contenere tra 4 e 6 cifre numeriche");
            }
        }

        // Atualizar apenas as configurações de PIN
        $configData['pin_enabled'] = $pinEnabled;
        $configData['pin_value'] = $pinEnabled ? $pinValue : '0000'; // Valor padrão quando desativado

        // Salvar no arquivo JSON 💾
        if (file_put_contents($configFile, json_encode($configData, JSON_PRETTY_PRINT))) {
            $success_message = $pinEnabled ?
                "✅ IN attivato con successo! Il sistema ora richiede l'autenticazione." :
                "🔓 PIN disabilitato con successo! L'accesso è ora disponibile.";
        } else {
            throw new Exception("❌ Errore durante il salvataggio delle impostazioni. Controlla i permessi del file.");
        }
    } catch (Exception $e) {
        $error_message = $e->getMessage();
    }
}

$page_title = "🔒 Gestione PIN";

$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-lock fs-2x text-primary"></i>
                    </span>
                </span>
                <div>
                    <h2 class="mb-1">🔐 Controllo di accesso PIN</h2>
                    <p class="text-gray-600">Gestisci l autenticazione PIN del sistema</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">⚙️ Impostazioni PIN</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="pin_enabled" name="pin_enabled" 
                            ' . ($configData['pin_enabled'] ? 'checked' : '') . '>
                        <label class="form-check-label" for="pin_enabled">
                            <strong>🔒 Abilita l autenticazione PIN</strong>
                        </label>
                    </div>
                    
                    <div id="pin_fields" style="display: ' . ($configData['pin_enabled'] ? 'block' : 'none') . ';">
                        <div class="mb-5">
                            <label for="pin_value" class="fs-6 fw-semibold mb-2">🔢 Inserisci il nuovo PIN</label>
                            <input type="password" class="form-control" 
                                id="pin_value" name="pin_value" 
                                placeholder="••••" 
                                value="' . ($configData['pin_enabled'] ? htmlspecialchars($configData['pin_value']) : '') . '"
                                maxlength="6" pattern="\d{4,6}">
                            <div class="form-text">Il PIN deve essere lungo tra 4 e 6 cifre numeriche</div>
                        </div>
                    </div>
                    
                    <div class="notice d-flex bg-light-warning rounded border-warning border border-dashed p-6 mt-6">
                        <i class="ki-outline ki-information-5 fs-2x text-warning 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>🔐 Gli utenti dovranno inserire il PIN per le impostazioni</li>
                                        <li>📱 La sicurezza del launcher sarà rafforzata</li>
                                        <li>👨‍💻 Ideale per ambienti con più utenti</li>

                                    </ul>
                                    <p>Quando <strong>desativado</strong>:</p>
                                    <ul>
                                        <li>🚪L accesso avverrà direttamente senza autenticazione</li>
                                        <li>🏠 Si consiglia di avvisare in anticipo i clienti</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 impostazioni
        </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['pin_enabled'] ? 'success' : 'danger') . '">
                            <i class="ki-outline ki-' . ($configData['pin_enabled'] ? 'lock' : 'unlock') . ' fs-2x text-' . ($configData['pin_enabled'] ? 'success' : 'danger') . '"></i>
                        </span>
                    </div>
                    <div class="flex-grow-1">
                        <h3 class="text-gray-800 fw-bold">Il PIN è attualmente: ' . 
                        ($configData['pin_enabled'] ? 
                            '<span class="text-success">ATTIVATO 🔒</span>' : 
                            '<span class="text-danger">DISABILI 🔓</span>') . 
                        '</h3>
                        ' . ($configData['pin_enabled'] ? 
                            '<p class="text-gray-600">PIN corrente impostato: ' . str_repeat('•', strlen($configData['pin_value'])) . '</p>' : '') . '
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener("DOMContentLoaded", function() {
    // Mostrar/ocultar campos do PIN conforme o toggle
    const pinToggle = document.getElementById("pin_enabled");
    const pinFields = document.getElementById("pin_fields");

    pinToggle.addEventListener("change", function() {
        pinFields.style.display = this.checked ? "block" : "none";
        if (!this.checked) {
            document.getElementById("pin_value").value = "";
        }
    });
});
</script>';

include 'includes/layout.php';
?>
