<?php
/**
 * Página de Agendamentos - 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') {
        $clientName = trim($_POST['client_name'] ?? '');
        $clientPhone = trim($_POST['client_phone'] ?? '');
        $serviceId = intval($_POST['service_id'] ?? 0);
        $professionalId = intval($_POST['professional_id'] ?? 0);
        $date = $_POST['appointment_date'] ?? '';
        $time = $_POST['appointment_time'] ?? '';
        $notes = trim($_POST['notes'] ?? '');
        
        if ($clientName && $date && $time) {
            $stmt = $pdo->prepare("INSERT INTO appointments (store_id, client_name, client_phone, service_id, professional_id, appointment_date, appointment_time, notes, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())");
            $stmt->execute([$storeId, $clientName, $clientPhone, $serviceId ?: null, $professionalId ?: null, $date, $time, $notes]);
            $_SESSION['flash_message'] = 'Agendamento criado com sucesso!';
            $_SESSION['flash_type'] = 'success';
        } else {
            $_SESSION['flash_message'] = 'Preencha os campos obrigatórios.';
            $_SESSION['flash_type'] = 'error';
        }
        header('Location: ' . strtok($_SERVER['REQUEST_URI'], '?'));
        exit;
    } elseif ($action === 'update_status' && isset($_POST['id'], $_POST['status'])) {
        $stmt = $pdo->prepare("UPDATE appointments SET status = ? WHERE id = ? AND store_id = ?");
        $stmt->execute([$_POST['status'], $_POST['id'], $storeId]);
        $_SESSION['flash_message'] = 'Status atualizado com sucesso!';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . $_SERVER['REQUEST_URI']);
        exit;
    } elseif ($action === 'delete' && isset($_POST['id'])) {
        $stmt = $pdo->prepare("DELETE FROM appointments WHERE id = ? AND store_id = ?");
        $stmt->execute([$_POST['id'], $storeId]);
        $_SESSION['flash_message'] = 'Agendamento removido com sucesso!';
        $_SESSION['flash_type'] = 'success';
        header('Location: ' . strtok($_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']);
}

// Filtros
$statusFilter = $_GET['status'] ?? '';
$dateFilter = $_GET['date'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 20;
$offset = ($page - 1) * $perPage;

// Construir query
$where = ['a.store_id = ?'];
$params = [$storeId];

if ($statusFilter) {
    $where[] = 'a.status = ?';
    $params[] = $statusFilter;
}

if ($dateFilter) {
    $where[] = 'DATE(a.appointment_date) = ?';
    $params[] = $dateFilter;
}

$whereClause = implode(' AND ', $where);

// Buscar total
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM appointments a WHERE $whereClause");
$countStmt->execute($params);
$total = $countStmt->fetchColumn();
$totalPages = ceil($total / $perPage);

// Buscar agendamentos
$appointmentsStmt = $pdo->prepare("
    SELECT a.*, s.name as service_name, s.duration, s.price, p.name as professional_name 
    FROM appointments a 
    LEFT JOIN services s ON a.service_id = s.id 
    LEFT JOIN professionals p ON a.professional_id = p.id 
    WHERE $whereClause
    ORDER BY a.appointment_date DESC, a.appointment_time ASC
    LIMIT $perPage OFFSET $offset
");
$appointmentsStmt->execute($params);
$appointments = $appointmentsStmt->fetchAll(PDO::FETCH_ASSOC);

// Buscar serviços e profissionais para o formulário
$servicesStmt = $pdo->prepare("SELECT * FROM services WHERE store_id = ? AND is_active = 1 ORDER BY name ASC");
$servicesStmt->execute([$storeId]);
$services = $servicesStmt->fetchAll(PDO::FETCH_ASSOC);

$profStmt = $pdo->prepare("SELECT * FROM professionals WHERE store_id = ? AND is_active = 1 ORDER BY name ASC");
$profStmt->execute([$storeId]);
$professionals = $profStmt->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Agendamentos';
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:calendar-mark-bold"></iconify-icon> Agendamentos</h1>
                <p>Gerencie todos os agendamentos da sua barbearia</p>
            </div>
            <button class="btn btn-primary" onclick="document.getElementById('addModal').style.display='flex'">
                <iconify-icon icon="solar:calendar-add-bold"></iconify-icon>
                Novo Agendamento
            </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; ?>
        
        <!-- Filtros -->
        <div class="card" style="margin-bottom: 1.5rem;">
            <form method="GET" style="display: flex; gap: 1rem; flex-wrap: wrap; align-items: flex-end;">
                <div class="form-group" style="margin: 0; flex: 1; min-width: 150px;">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-input">
                        <option value="">Todos</option>
                        <option value="pending" <?php echo $statusFilter === 'pending' ? 'selected' : ''; ?>>Pendente</option>
                        <option value="confirmed" <?php echo $statusFilter === 'confirmed' ? 'selected' : ''; ?>>Confirmado</option>
                        <option value="completed" <?php echo $statusFilter === 'completed' ? 'selected' : ''; ?>>Concluído</option>
                        <option value="cancelled" <?php echo $statusFilter === 'cancelled' ? 'selected' : ''; ?>>Cancelado</option>
                    </select>
                </div>
                <div class="form-group" style="margin: 0; flex: 1; min-width: 150px;">
                    <label class="form-label">Data</label>
                    <input type="date" name="date" class="form-input" value="<?php echo $dateFilter; ?>">
                </div>
                <button type="submit" class="btn btn-secondary">
                    <iconify-icon icon="solar:filter-bold"></iconify-icon>
                    Filtrar
                </button>
                <?php if ($statusFilter || $dateFilter): ?>
                <a href="/pages/agendamentos.php" class="btn btn-secondary">
                    <iconify-icon icon="solar:close-circle-bold"></iconify-icon>
                    Limpar
                </a>
                <?php endif; ?>
            </form>
        </div>
        
        <?php if (empty($appointments)): ?>
        <div class="empty-state">
            <iconify-icon icon="solar:calendar-mark-bold"></iconify-icon>
            <h3>Nenhum agendamento encontrado</h3>
            <p>Não há agendamentos com os filtros selecionados.</p>
            <button class="btn btn-primary" onclick="document.getElementById('addModal').style.display='flex'" style="margin-top: 1rem;">
                <iconify-icon icon="solar:calendar-add-bold"></iconify-icon>
                Criar Agendamento
            </button>
        </div>
        <?php else: ?>
        <div class="card">
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Data/Hora</th>
                            <th>Cliente</th>
                            <th>Serviço</th>
                            <th>Profissional</th>
                            <th>Status</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($appointments as $apt): ?>
                        <tr>
                            <td>
                                <div style="font-weight: 600;"><?php echo date('d/m/Y', strtotime($apt['appointment_date'])); ?></div>
                                <div style="color: var(--text-muted); font-size: 0.9rem;">
                                    <iconify-icon icon="solar:clock-circle-bold"></iconify-icon>
                                    <?php echo substr($apt['appointment_time'], 0, 5); ?>
                                </div>
                            </td>
                            <td>
                                <div style="font-weight: 600;"><?php echo htmlspecialchars($apt['client_name']); ?></div>
                                <?php if ($apt['client_phone']): ?>
                                <div style="color: var(--text-muted); font-size: 0.9rem;">
                                    <iconify-icon icon="solar:phone-bold"></iconify-icon>
                                    <?php echo htmlspecialchars($apt['client_phone']); ?>
                                </div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if ($apt['service_name']): ?>
                                <div><?php echo htmlspecialchars($apt['service_name']); ?></div>
                                <div style="color: var(--success); font-weight: 600;">R$ <?php echo number_format($apt['price'] ?? 0, 2, ',', '.'); ?></div>
                                <?php else: ?>
                                <span style="color: var(--text-muted);">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php echo $apt['professional_name'] ? htmlspecialchars($apt['professional_name']) : '<span style="color: var(--text-muted);">-</span>'; ?>
                            </td>
                            <td>
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="action" value="update_status">
                                    <input type="hidden" name="id" value="<?php echo $apt['id']; ?>">
                                    <select name="status" class="form-input" style="padding: 0.25rem 0.5rem; font-size: 0.85rem;" onchange="this.form.submit()">
                                        <option value="pending" <?php echo $apt['status'] === 'pending' ? 'selected' : ''; ?>>Pendente</option>
                                        <option value="confirmed" <?php echo $apt['status'] === 'confirmed' ? 'selected' : ''; ?>>Confirmado</option>
                                        <option value="completed" <?php echo $apt['status'] === 'completed' ? 'selected' : ''; ?>>Concluído</option>
                                        <option value="cancelled" <?php echo $apt['status'] === 'cancelled' ? 'selected' : ''; ?>>Cancelado</option>
                                    </select>
                                </form>
                            </td>
                            <td>
                                <form method="POST" style="display: inline;" onsubmit="return confirm('Tem certeza que deseja excluir este agendamento?');">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?php echo $apt['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>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <?php if ($totalPages > 1): ?>
            <div style="display: flex; justify-content: center; gap: 0.5rem; margin-top: 1.5rem;">
                <?php if ($page > 1): ?>
                <a href="?page=<?php echo $page - 1; ?>&status=<?php echo $statusFilter; ?>&date=<?php echo $dateFilter; ?>" class="btn btn-secondary btn-sm">
                    <iconify-icon icon="solar:arrow-left-bold"></iconify-icon>
                </a>
                <?php endif; ?>
                
                <span style="padding: 0.5rem 1rem;">Página <?php echo $page; ?> de <?php echo $totalPages; ?></span>
                
                <?php if ($page < $totalPages): ?>
                <a href="?page=<?php echo $page + 1; ?>&status=<?php echo $statusFilter; ?>&date=<?php echo $dateFilter; ?>" class="btn btn-secondary btn-sm">
                    <iconify-icon icon="solar:arrow-right-bold"></iconify-icon>
                </a>
                <?php endif; ?>
            </div>
            <?php endif; ?>
        </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; overflow-y: auto; padding: 2rem;">
        <div class="card" style="width: 100%; max-width: 500px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem;">
                <h2 style="font-size: 1.25rem;">Novo Agendamento</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 Cliente *</label>
                    <input type="text" name="client_name" class="form-input" placeholder="Nome completo" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Telefone</label>
                    <input type="tel" name="client_phone" class="form-input" placeholder="(11) 99999-9999">
                </div>
                
                <div class="form-group">
                    <label class="form-label">Serviço</label>
                    <select name="service_id" class="form-input">
                        <option value="">Selecione um serviço</option>
                        <?php foreach ($services as $service): ?>
                        <option value="<?php echo $service['id']; ?>">
                            <?php echo htmlspecialchars($service['name']); ?> - R$ <?php echo number_format($service['price'], 2, ',', '.'); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Profissional</label>
                    <select name="professional_id" class="form-input">
                        <option value="">Selecione um profissional</option>
                        <?php foreach ($professionals as $prof): ?>
                        <option value="<?php echo $prof['id']; ?>"><?php echo htmlspecialchars($prof['name']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 1rem;">
                    <div class="form-group">
                        <label class="form-label">Data *</label>
                        <input type="date" name="appointment_date" class="form-input" value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                    <div class="form-group">
                        <label class="form-label">Horário *</label>
                        <input type="time" name="appointment_time" class="form-input" value="09:00" required>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Observações</label>
                    <textarea name="notes" class="form-input" rows="2" placeholder="Observações sobre o agendamento..."></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'; ?>
