<?php
/**
 * Página de Serviços - MontaLoja SaaS
 */
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 = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'add') {
        $name = trim($_POST['name'] ?? '');
        $price = floatval($_POST['price'] ?? 0);
        $duration = intval($_POST['duration'] ?? 30);
        $description = trim($_POST['description'] ?? '');
        
        if ($name && $price > 0) {
            $stmt = $pdo->prepare("INSERT INTO services (store_id, name, price, duration, description, is_active, created_at) VALUES (?, ?, ?, ?, ?, 1, NOW())");
            $stmt->execute([$storeId, $name, $price, $duration, $description]);
            $_SESSION['flash_message'] = 'Serviço adicionado com sucesso!';
            $_SESSION['flash_type'] = 'success';
        } else {
            $_SESSION['flash_message'] = 'Preencha o nome e preço do serviço.';
            $_SESSION['flash_type'] = 'error';
        }
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    } elseif ($action === 'delete' && isset($_POST['id'])) {
        $stmt = $pdo->prepare("DELETE FROM services WHERE id = ? AND store_id = ?");
        $stmt->execute([$_POST['id'], $storeId]);
        $_SESSION['flash_message'] = 'Serviço removido com sucesso!';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    } elseif ($action === 'toggle' && isset($_POST['id'])) {
        $stmt = $pdo->prepare("UPDATE services SET is_active = NOT is_active WHERE id = ? AND store_id = ?");
        $stmt->execute([$_POST['id'], $storeId]);
        $_SESSION['flash_message'] = 'Status do serviço atualizado!';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    }
}

// Verificar mensagens flash
if (isset($_SESSION['flash_message'])) {
    $message = $_SESSION['flash_message'];
    $messageType = $_SESSION['flash_type'] ?? 'success';
    unset($_SESSION['flash_message'], $_SESSION['flash_type']);
}

// Buscar serviços
$servicesStmt = $pdo->prepare("SELECT * FROM services WHERE store_id = ? ORDER BY sort_order ASC, name ASC");
$servicesStmt->execute([$storeId]);
$services = $servicesStmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Serviços';
include __DIR__ . '/../includes/dashboard-header.php';
?>

    <main class="main-content">
        <div class="page-header" style="display: flex; justify-content: space-between; align-items: center;">
            <div>
                <h1><iconify-icon icon="solar:scissors-bold"></iconify-icon> Serviços</h1>
                <p>Gerencie os serviços oferecidos pela sua barbearia</p>
            </div>
            <button class="btn btn-primary" onclick="document.getElementById('addModal').style.display='flex'">
                <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                Novo Serviço
            </button>
        </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; ?>
        
        <?php if (empty($services)): ?>
        <div class="empty-state">
            <iconify-icon icon="solar:scissors-bold"></iconify-icon>
            <h3>Nenhum serviço cadastrado</h3>
            <p>Adicione seu primeiro serviço para começar a receber agendamentos.</p>
            <button class="btn btn-primary" onclick="document.getElementById('addModal').style.display='flex'" style="margin-top: 1rem;">
                <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                Adicionar Serviço
            </button>
        </div>
        <?php else: ?>
        <div class="card">
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Serviço</th>
                            <th>Duração</th>
                            <th>Preço</th>
                            <th>Status</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($services as $service): ?>
                        <tr>
                            <td>
                                <div style="font-weight: 600;"><?php echo htmlspecialchars($service['name']); ?></div>
                                <?php if ($service['description']): ?>
                                <div style="font-size: 0.85rem; color: var(--text-muted);"><?php echo htmlspecialchars($service['description']); ?></div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <span style="display: flex; align-items: center; gap: 0.5rem;">
                                    <iconify-icon icon="solar:clock-circle-bold" style="color: var(--primary);"></iconify-icon>
                                    <?php echo $service['duration']; ?> min
                                </span>
                            </td>
                            <td style="font-weight: 600; color: var(--success);">
                                R$ <?php echo number_format($service['price'], 2, ',', '.'); ?>
                            </td>
                            <td>
                                <span class="badge <?php echo $service['is_active'] ? 'badge-success' : 'badge-error'; ?>">
                                    <?php echo $service['is_active'] ? 'Ativo' : 'Inativo'; ?>
                                </span>
                            </td>
                            <td>
                                <div style="display: flex; gap: 0.5rem;">
                                    <form method="POST" style="display: inline;">
                                        <input type="hidden" name="action" value="toggle">
                                        <input type="hidden" name="id" value="<?php echo $service['id']; ?>">
                                        <button type="submit" class="btn btn-secondary btn-sm" title="<?php echo $service['is_active'] ? 'Desativar' : 'Ativar'; ?>">
                                            <iconify-icon icon="<?php echo $service['is_active'] ? 'solar:eye-closed-bold' : 'solar:eye-bold'; ?>"></iconify-icon>
                                        </button>
                                    </form>
                                    <form method="POST" style="display: inline;" onsubmit="return confirm('Tem certeza que deseja excluir este serviço?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?php echo $service['id']; ?>">
                                        <button type="submit" class="btn btn-secondary btn-sm" style="color: var(--error);">
                                            <iconify-icon icon="solar:trash-bin-2-bold"></iconify-icon>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php endif; ?>
    </main>
    
    <!-- Modal Adicionar -->
    <div id="addModal" style="display: none; position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); z-index: 1000; align-items: center; justify-content: center;">
        <div class="card" style="width: 100%; max-width: 500px; margin: 2rem;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                <h2 style="font-size: 1.25rem;">Novo Serviço</h2>
                <button onclick="document.getElementById('addModal').style.display='none'" style="background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 1.5rem;">
                    <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                </button>
            </div>
            <form method="POST">
                <input type="hidden" name="action" value="add">
                <div class="form-group">
                    <label class="form-label">Nome do Serviço *</label>
                    <input type="text" name="name" class="form-input" placeholder="Ex: Corte Masculino" required>
                </div>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Preço (R$) *</label>
                        <input type="number" name="price" class="form-input" placeholder="35.00" step="0.01" min="0" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Duração (min)</label>
                        <input type="number" name="duration" class="form-input" value="30" min="5" step="5">
                    </div>
                </div>
                <div class="form-group">
                    <label class="form-label">Descrição</label>
                    <textarea name="description" class="form-input" rows="3" placeholder="Descrição opcional do serviço..."></textarea>
                </div>
                <div style="display: flex; gap: 1rem; justify-content: flex-end;">
                    <button type="button" class="btn btn-secondary" onclick="document.getElementById('addModal').style.display='none'">Cancelar</button>
                    <button type="submit" class="btn btn-primary">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        Salvar
                    </button>
                </div>
            </form>
        </div>
    </div>

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