<?php
/**
 * Página de Configurações - MontaLoja SaaS
 * Versão Responsiva (Loja e Barbearia)
 */
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/check-access.php';

$pdo = getDB();
$userId = $_SESSION['user_id'] ?? null;
$storeId = $_SESSION['store_id'] ?? null;

if (!$userId || !$storeId) {
    header('Location: /pages/login.php');
    exit;
}

$userStmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$userStmt->execute([$userId]);
$user = $userStmt->fetch(PDO::FETCH_ASSOC);

$storeStmt = $pdo->prepare("SELECT * FROM stores WHERE id = ?");
$storeStmt->execute([$storeId]);
$store = $storeStmt->fetch(PDO::FETCH_ASSOC);

// Processar ações
$message = '';
$messageType = '';
$activeTab = $_GET['tab'] ?? 'store';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'update_store') {
        $name = trim($_POST['name'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $address = trim($_POST['address'] ?? '');
        $description = trim($_POST['description'] ?? '');
        
        if ($name) {
            $stmt = $pdo->prepare("UPDATE stores SET name = ?, phone = ?, email = ?, address = ?, description = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$name, $phone, $email, $address, $description, $storeId]);
            $message = 'Dados da loja atualizados!';
            $messageType = 'success';
            
            // Recarregar dados
            $storeStmt->execute([$storeId]);
            $store = $storeStmt->fetch(PDO::FETCH_ASSOC);
        }
        $activeTab = 'store';
        
    } elseif ($action === 'update_user') {
        $name = trim($_POST['name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $phone = trim($_POST['phone'] ?? '');
        
        if ($name && $email) {
            $stmt = $pdo->prepare("UPDATE users SET name = ?, email = ?, phone = ?, updated_at = NOW() WHERE id = ?");
            $stmt->execute([$name, $email, $phone, $userId]);
            $message = 'Perfil atualizado!';
            $messageType = 'success';
            
            $userStmt->execute([$userId]);
            $user = $userStmt->fetch(PDO::FETCH_ASSOC);
        }
        $activeTab = 'profile';
        
    } elseif ($action === 'change_password') {
        $currentPassword = $_POST['current_password'] ?? '';
        $newPassword = $_POST['new_password'] ?? '';
        $confirmPassword = $_POST['confirm_password'] ?? '';
        
        if (password_verify($currentPassword, $user['password_hash'])) {
            if ($newPassword === $confirmPassword && strlen($newPassword) >= 6) {
                $hashedPassword = password_hash($newPassword, PASSWORD_DEFAULT);
                $stmt = $pdo->prepare("UPDATE users SET password_hash = ?, updated_at = NOW() WHERE id = ?");
                $stmt->execute([$hashedPassword, $userId]);
                $message = 'Senha alterada com sucesso!';
                $messageType = 'success';
            } else {
                $message = 'As senhas não coincidem ou são muito curtas (mín. 6 caracteres).';
                $messageType = 'error';
            }
        } else {
            $message = 'Senha atual incorreta.';
            $messageType = 'error';
        }
        $activeTab = 'security';
        
    } elseif ($action === 'update_hours') {
        $hours = $_POST['hours'] ?? [];
        $hoursJson = json_encode($hours);
        $stmt = $pdo->prepare("UPDATE stores SET business_hours = ? WHERE id = ?");
        $stmt->execute([$hoursJson, $storeId]);
        $message = 'Horários atualizados!';
        $messageType = 'success';
        $activeTab = 'hours';
        
    } elseif ($action === 'update_notifications') {
        $emailNotifications = isset($_POST['email_notifications']) ? 1 : 0;
        $smsNotifications = isset($_POST['sms_notifications']) ? 1 : 0;
        $whatsappNotifications = isset($_POST['whatsapp_notifications']) ? 1 : 0;
        
        $stmt = $pdo->prepare("UPDATE stores SET email_notifications = ?, sms_notifications = ?, whatsapp_notifications = ? WHERE id = ?");
        $stmt->execute([$emailNotifications, $smsNotifications, $whatsappNotifications, $storeId]);
        $message = 'Preferências de notificação atualizadas!';
        $messageType = 'success';
        $activeTab = 'notifications';
    }
}

$businessHours = json_decode($store['business_hours'] ?? '{}', true) ?: [];

$pageTitle = 'Configurações';
include __DIR__ . '/../includes/dashboard-header.php';
?>

<?php include __DIR__ . '/../includes/responsive-styles.php'; ?>


<style>
.settings-container {
    display: grid;
    grid-template-columns: 250px 1fr;
    gap: 1.5rem;
}

.settings-nav {
    background: var(--card-bg);
    border-radius: var(--radius);
    padding: 1rem;
    height: fit-content;
    position: sticky;
    top: 1rem;
}

.settings-nav-item {
    display: flex;
    align-items: center;
    border-radius: 8px;
    gap: 0.75rem;
    padding: 0.75rem 1rem;
    border-radius: var(--radius);
    color: var(--text);
    text-decoration: none;
    transition: all 0.2s;
    margin-bottom: 0.25rem;
}

.settings-nav-item:hover {
    background: var(--bg);
    background: var(--primary);
    border-radius: 8px;
    color: white;
}

.settings-nav-item.active {
    background: var(--primary);
    border-radius: 8px;
    color: white;
}

.settings-content {
    min-width: 0;
}

.settings-section {
    background: var(--card-bg);
    border-radius: var(--radius);
    padding: 1.5rem;
    display: none;
}

.settings-section.active {
    display: block;
}

.settings-section h2 {
    font-size: 1.25rem;
    margin-bottom: 1.5rem;
    display: flex;
    align-items: center;
    gap: 0.5rem;
}

.toggle-switch {
    position: relative;
    width: 50px;
    height: 26px;
}

.toggle-switch input {
    opacity: 0;
    width: 0;
    height: 0;
}

.toggle-slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: var(--border);
    transition: 0.3s;
    border-radius: 26px;
}

.toggle-slider:before {
    position: absolute;
    content: "";
    height: 20px;
    width: 20px;
    left: 3px;
    bottom: 3px;
    background-color: white;
    transition: 0.3s;
    border-radius: 50%;
}

.toggle-switch input:checked + .toggle-slider {
    background-color: var(--primary);
}

.toggle-switch input:checked + .toggle-slider:before {
    transform: translateX(24px);
}

.notification-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1rem 0;
    border-bottom: 1px solid var(--border);
}

.notification-option:last-child {
    border-bottom: none;
}

.notification-info h4 {
    font-weight: 600;
    margin-bottom: 0.25rem;
}

.notification-info p {
    font-size: 0.85rem;
    color: var(--text-muted);
}

.hours-grid {
    display: grid;
    gap: 0.75rem;
}

.hours-row {
    display: grid;
    grid-template-columns: 100px 1fr 1fr auto;
    gap: 0.75rem;
    align-items: center;
}

.hours-row input[type="time"] {
    padding: 0.5rem;
}

@media (max-width: 768px) {
    .settings-container {
        grid-template-columns: 1fr;
    }
    
    .settings-nav {
        position: static;
        display: flex;
        overflow-x: auto;
        gap: 0.5rem;
        padding: 0.75rem;
    }
    
    .settings-nav-item {
        white-space: nowrap;
        padding: 0.5rem 1rem;
        margin: 0;
    }
    
    .hours-row {
        grid-template-columns: 1fr;
        gap: 0.5rem;
        padding: 0.75rem;
        background: var(--bg);
        border-radius: var(--radius);
    }
    
    .hours-row .form-label {
        font-weight: 600;
    }
}
</style>

    <main class="main-content">
        <div class="page-header">
            <h1><iconify-icon icon="solar:settings-bold"></iconify-icon> Configurações</h1>
            <p>Gerencie as configurações da sua conta e loja</p>
        </div>
        
        <?php if ($message): ?>
        <div class="alert alert-<?php echo $messageType; ?>">
            <iconify-icon icon="<?php echo $messageType === 'success' ? 'solar:check-circle-bold' : 'solar:danger-circle-bold'; ?>"></iconify-icon>
            <?php echo $message; ?>
        </div>
        <?php endif; ?>
        
        <div class="settings-container">
            <!-- Navegação -->
            <nav class="settings-nav">
                <a href="?tab=store" class="settings-nav-item <?php echo $activeTab === 'store' ? 'active' : ''; ?>">
                    <iconify-icon icon="solar:shop-bold"></iconify-icon>
                    <span>Loja</span>
                </a>
                <a href="?tab=profile" class="settings-nav-item <?php echo $activeTab === 'profile' ? 'active' : ''; ?>">
                    <iconify-icon icon="solar:user-bold"></iconify-icon>
                    <span>Perfil</span>
                </a>
                <a href="?tab=security" class="settings-nav-item <?php echo $activeTab === 'security' ? 'active' : ''; ?>">
                    <iconify-icon icon="solar:lock-bold"></iconify-icon>
                    <span>Segurança</span>
                </a>
                <a href="?tab=hours" class="settings-nav-item <?php echo $activeTab === 'hours' ? 'active' : ''; ?>">
                    <iconify-icon icon="solar:clock-circle-bold"></iconify-icon>
                    <span>Horários</span>
                </a>
                <a href="?tab=notifications" class="settings-nav-item <?php echo $activeTab === 'notifications' ? 'active' : ''; ?>">
                    <iconify-icon icon="solar:bell-bold"></iconify-icon>
                    <span>Notificações</span>
                </a>
            </nav>
            
            <!-- Conteúdo -->
            <div class="settings-content">
                <!-- Dados da Loja -->
                <div class="settings-section <?php echo $activeTab === 'store' ? 'active' : ''; ?>">
                    <h2><iconify-icon icon="solar:shop-bold"></iconify-icon> Dados da Loja</h2>
                    <form method="POST">
                        <input type="hidden" name="action" value="update_store">
                        
                        <div class="form-group">
                            <label class="form-label">Nome da Loja *</label>
                            <input type="text" name="name" class="form-input" value="<?php echo htmlspecialchars($store['name'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="form-grid-2">
                            <div class="form-group">
                                <label class="form-label">Telefone</label>
                                <input type="tel" name="phone" class="form-input" value="<?php echo htmlspecialchars($store['phone'] ?? ''); ?>">
                            </div>
                            <div class="form-group">
                                <label class="form-label">E-mail</label>
                                <input type="email" name="email" class="form-input" value="<?php echo htmlspecialchars($store['email'] ?? ''); ?>">
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Endereço</label>
                            <input type="text" name="address" class="form-input" value="<?php echo htmlspecialchars($store['address'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label class="form-label">Descrição</label>
                            <textarea name="description" class="form-input" rows="3"><?php echo htmlspecialchars($store['description'] ?? ''); ?></textarea>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">
                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                            Salvar Alterações
                        </button>
                    </form>
                </div>
                
                <!-- Perfil -->
                <div class="settings-section <?php echo $activeTab === 'profile' ? 'active' : ''; ?>">
                    <h2><iconify-icon icon="solar:user-bold"></iconify-icon> Meu Perfil</h2>
                    <form method="POST">
                        <input type="hidden" name="action" value="update_user">
                        
                        <div class="form-group">
                            <label class="form-label">Nome Completo *</label>
                            <input type="text" name="name" class="form-input" value="<?php echo htmlspecialchars($user['name'] ?? ''); ?>" required>
                        </div>
                        
                        <div class="form-grid-2">
                            <div class="form-group">
                                <label class="form-label">E-mail *</label>
                                <input type="email" name="email" class="form-input" value="<?php echo htmlspecialchars($user['email'] ?? ''); ?>" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Telefone</label>
                                <input type="tel" name="phone" class="form-input" value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>">
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">
                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                            Salvar Alterações
                        </button>
                    </form>
                </div>
                
                <!-- Segurança -->
                <div class="settings-section <?php echo $activeTab === 'security' ? 'active' : ''; ?>">
                    <h2><iconify-icon icon="solar:lock-bold"></iconify-icon> Segurança</h2>
                    <form method="POST">
                        <input type="hidden" name="action" value="change_password">
                        
                        <div class="form-group">
                            <label class="form-label">Senha Atual</label>
                            <input type="password" name="current_password" class="form-input" required>
                        </div>
                        
                        <div class="form-grid-2">
                            <div class="form-group">
                                <label class="form-label">Nova Senha</label>
                                <input type="password" name="new_password" class="form-input" minlength="6" required>
                            </div>
                            <div class="form-group">
                                <label class="form-label">Confirmar Nova Senha</label>
                                <input type="password" name="confirm_password" class="form-input" minlength="6" required>
                            </div>
                        </div>
                        
                        <button type="submit" class="btn btn-primary">
                            <iconify-icon icon="solar:lock-bold"></iconify-icon>
                            Alterar Senha
                        </button>
                    </form>
                </div>
                
                <!-- Horários -->
                <div class="settings-section <?php echo $activeTab === 'hours' ? 'active' : ''; ?>">
                    <h2><iconify-icon icon="solar:clock-circle-bold"></iconify-icon> Horário de Funcionamento</h2>
                    <form method="POST">
                        <input type="hidden" name="action" value="update_hours">
                        
                        <div class="hours-grid">
                            <?php
                            $days = [
                                'monday' => 'Segunda',
                                'tuesday' => 'Terça',
                                'wednesday' => 'Quarta',
                                'thursday' => 'Quinta',
                                'friday' => 'Sexta',
                                'saturday' => 'Sábado',
                                'sunday' => 'Domingo'
                            ];
                            foreach ($days as $key => $label):
                                $dayData = $businessHours[$key] ?? ['open' => '09:00', 'close' => '18:00', 'closed' => false];
                            ?>
                            <div class="hours-row">
                                <label class="form-label" style="margin: 0;"><?php echo $label; ?></label>
                                <input type="time" name="hours[<?php echo $key; ?>][open]" class="form-input" value="<?php echo $dayData['open'] ?? '09:00'; ?>">
                                <input type="time" name="hours[<?php echo $key; ?>][close]" class="form-input" value="<?php echo $dayData['close'] ?? '18:00'; ?>">
                                <label class="toggle-switch">
                                    <input type="checkbox" name="hours[<?php echo $key; ?>][closed]" <?php echo !empty($dayData['closed']) ? 'checked' : ''; ?>>
                                    <span class="toggle-slider"></span>
                                </label>
                                <span style="font-size: 0.85rem; color: var(--text-muted);">Fechado</span>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        
                        <button type="submit" class="btn btn-primary" style="margin-top: 1.5rem;">
                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                            Salvar Horários
                        </button>
                    </form>
                </div>
                
                <!-- Notificações -->
                <div class="settings-section <?php echo $activeTab === 'notifications' ? 'active' : ''; ?>">
                    <h2><iconify-icon icon="solar:bell-bold"></iconify-icon> Notificações</h2>
                    <form method="POST">
                        <input type="hidden" name="action" value="update_notifications">
                        
                        <div class="notification-option">
                            <div class="notification-info">
                                <h4>Notificações por E-mail</h4>
                                <p>Receba alertas de novos pedidos e agendamentos por e-mail</p>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" name="email_notifications" <?php echo !empty($store['email_notifications']) ? 'checked' : ''; ?>>
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                        
                        <div class="notification-option">
                            <div class="notification-info">
                                <h4>Notificações por SMS</h4>
                                <p>Receba alertas urgentes por SMS</p>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" name="sms_notifications" <?php echo !empty($store['sms_notifications']) ? 'checked' : ''; ?>>
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                        
                        <div class="notification-option">
                            <div class="notification-info">
                                <h4>Notificações por WhatsApp</h4>
                                <p>Receba alertas pelo WhatsApp</p>
                            </div>
                            <label class="toggle-switch">
                                <input type="checkbox" name="whatsapp_notifications" <?php echo !empty($store['whatsapp_notifications']) ? 'checked' : ''; ?>>
                                <span class="toggle-slider"></span>
                            </label>
                        </div>
                        
                        <button type="submit" class="btn btn-primary" style="margin-top: 1.5rem;">
                            <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                            Salvar Preferências
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </main>

<?php include __DIR__ . '/../includes/dashboard-footer.php'; ?>
