<?php
/**
 * Página de Agenda - MontaLoja SaaS
 * Versão Responsiva
 */
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;
}

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

// Verificar se tabelas existem
$appointmentsTableExists = false;
$servicesTableExists = false;
$teamTableExists = false;

try {
    $check = $pdo->query("SHOW TABLES LIKE 'appointments'");
    $appointmentsTableExists = $check->rowCount() > 0;
    
    $check = $pdo->query("SHOW TABLES LIKE 'services'");
    $servicesTableExists = $check->rowCount() > 0;
    
    $check = $pdo->query("SHOW TABLES LIKE 'team_members'");
    $teamTableExists = $check->rowCount() > 0;
} catch (Exception $e) {}

// Data selecionada
$selectedDate = $_GET['date'] ?? date('Y-m-d');
$selectedProfessional = $_GET['professional'] ?? '';

// Processar ações
$message = '';
$messageType = '';
$services = [];
$team = [];
$appointments = [];
$todayStats = ['total' => 0, 'confirmed' => 0, 'completed' => 0, 'revenue' => 0];

if ($appointmentsTableExists) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $action = $_POST['action'] ?? '';
        
        try {
            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['date'] ?? date('Y-m-d');
                $time = $_POST['time'] ?? '';
                $notes = trim($_POST['notes'] ?? '');
                
                if ($clientName && $serviceId && $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 (?, ?, ?, ?, ?, ?, ?, ?, 'scheduled', NOW())");
                    $stmt->execute([$storeId, $clientName, $clientPhone, $serviceId, $professionalId ?: null, $date, $time, $notes]);
                    $message = 'Agendamento criado com sucesso!';
                    $messageType = 'success';
                }
            } elseif ($action === 'update_status' && isset($_POST['id'])) {
                $newStatus = $_POST['status'] ?? 'scheduled';
                $stmt = $pdo->prepare("UPDATE appointments SET status = ? WHERE id = ? AND store_id = ?");
                $stmt->execute([$newStatus, $_POST['id'], $storeId]);
                $message = 'Status atualizado!';
                $messageType = 'success';
            } elseif ($action === 'delete' && isset($_POST['id'])) {
                $stmt = $pdo->prepare("DELETE FROM appointments WHERE id = ? AND store_id = ?");
                $stmt->execute([$_POST['id'], $storeId]);
                $message = 'Agendamento removido!';
                $messageType = 'success';
            }
        } catch (Exception $e) {
            $message = 'Erro ao processar: ' . $e->getMessage();
            $messageType = 'error';
        }
    }
}

// Buscar dados
if ($servicesTableExists) {
    try {
        $servicesStmt = $pdo->prepare("SELECT * FROM services WHERE store_id = ? AND is_active = 1 ORDER BY name");
        $servicesStmt->execute([$storeId]);
        $services = $servicesStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {}
}

if ($teamTableExists) {
    try {
        $teamStmt = $pdo->prepare("SELECT * FROM team_members WHERE store_id = ? AND is_active = 1 ORDER BY name");
        $teamStmt->execute([$storeId]);
        $team = $teamStmt->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {}
}

// Buscar agendamentos do dia
if ($appointmentsTableExists) {
    try {
        $appointmentsSql = "SELECT a.*, s.name as service_name, s.price, s.duration, t.name as professional_name 
                            FROM appointments a 
                            LEFT JOIN services s ON a.service_id = s.id 
                            LEFT JOIN team_members t ON a.professional_id = t.id 
                            WHERE a.store_id = ? AND a.appointment_date = ?";
        $params = [$storeId, $selectedDate];

        if ($selectedProfessional) {
            $appointmentsSql .= " AND a.professional_id = ?";
            $params[] = $selectedProfessional;
        }

        $appointmentsSql .= " ORDER BY a.appointment_time ASC";
        $appointmentsStmt = $pdo->prepare($appointmentsSql);
        $appointmentsStmt->execute($params);
        $appointments = $appointmentsStmt->fetchAll(PDO::FETCH_ASSOC);

        // Estatísticas do dia
        $todayStats = [
            'total' => count($appointments),
            'confirmed' => count(array_filter($appointments, fn($a) => $a['status'] === 'confirmed')),
            'completed' => count(array_filter($appointments, fn($a) => $a['status'] === 'completed')),
            'revenue' => array_sum(array_map(fn($a) => $a['status'] === 'completed' ? ($a['price'] ?? 0) : 0, $appointments))
        ];
    } catch (Exception $e) {}
}

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

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

<style>
.agenda-grid {
    display: grid;
    gap: 1rem;
}

.date-nav {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    background: var(--card-bg);
    border-radius: var(--radius);
    padding: 0.5rem;
    flex-wrap: wrap;
}

.date-nav input[type="date"] {
    border: none;
    background: transparent;
    font-size: 1rem;
    font-weight: 600;
    color: var(--text);
    cursor: pointer;
}

.date-nav .btn {
    padding: 0.5rem;
}

.time-slot {
    display: flex;
    align-items: stretch;
    gap: 1rem;
    padding: 1rem;
    background: var(--card-bg);
    border-radius: var(--radius);
    border-left: 4px solid var(--border);
}

.time-slot.confirmed {
    border-left-color: #22C55E;
}

.time-slot.scheduled {
    border-left-color: #3B82F6;
}

.time-slot.completed {
    border-left-color: #6B7280;
    opacity: 0.7;
}

.time-slot.cancelled {
    border-left-color: #EF4444;
    opacity: 0.5;
}

.time-slot-time {
    font-size: 1.1rem;
    font-weight: 700;
    color: var(--primary);
    min-width: 70px;
}

.time-slot-content {
    flex: 1;
    min-width: 0;
}

.time-slot-client {
    font-weight: 600;
    font-size: 1rem;
    margin-bottom: 0.25rem;
}

.time-slot-service {
    color: var(--text-muted);
    font-size: 0.9rem;
}

.time-slot-meta {
    display: flex;
    flex-wrap: wrap;
    gap: 0.75rem;
    margin-top: 0.5rem;
    font-size: 0.85rem;
}

.time-slot-meta-item {
    display: flex;
    align-items: center;
    gap: 0.25rem;
    color: var(--text-muted);
}

.time-slot-actions {
    display: flex;
    gap: 0.5rem;
    align-items: flex-start;
}

.status-select {
    padding: 0.35rem 0.5rem;
    border-radius: var(--radius-sm);
    border: 1px solid var(--border);
    background: var(--bg);
    font-size: 0.85rem;
    cursor: pointer;
}

.empty-slot {
    text-align: center;
    padding: 3rem 1rem;
    color: var(--text-muted);
}

@media (max-width: 600px) {
    .time-slot {
        flex-direction: column;
        gap: 0.75rem;
    }
    
    .time-slot-time {
        display: flex;
        align-items: center;
        gap: 0.5rem;
    }
    
    .time-slot-actions {
        flex-wrap: wrap;
    }
    
    .date-nav {
        justify-content: center;
    }
}
</style>

    <main class="main-content">
        <div class="page-header page-header-flex">
            <div>
                <h1><iconify-icon icon="solar:calendar-bold"></iconify-icon> Agenda</h1>
                <p>Gerencie os agendamentos do dia</p>
            </div>
            <button class="btn btn-primary" onclick="openAddModal()">
                <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                <span>Novo Agendamento</span>
            </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; ?>
        
        <!-- Navegação de Data -->
        <div class="filter-bar">
            <div class="date-nav">
                <button class="btn btn-secondary" onclick="changeDate(-1)">
                    <iconify-icon icon="solar:arrow-left-bold"></iconify-icon>
                </button>
                <input type="date" id="dateSelector" value="<?php echo $selectedDate; ?>" onchange="goToDate(this.value)">
                <button class="btn btn-secondary" onclick="changeDate(1)">
                    <iconify-icon icon="solar:arrow-right-bold"></iconify-icon>
                </button>
                <button class="btn btn-secondary" onclick="goToDate('<?php echo date('Y-m-d'); ?>')">
                    Hoje
                </button>
            </div>
            
            <?php if (!empty($team)): ?>
            <select class="form-input" style="max-width: 200px;" onchange="filterByProfessional(this.value)">
                <option value="">Todos Profissionais</option>
                <?php foreach ($team as $member): ?>
                <option value="<?php echo $member['id']; ?>" <?php echo $selectedProfessional == $member['id'] ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($member['name']); ?>
                </option>
                <?php endforeach; ?>
            </select>
            <?php endif; ?>
        </div>
        
        <!-- Stats do Dia -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-icon">
                    <iconify-icon icon="solar:calendar-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo $todayStats['total']; ?></span>
                    <span class="stat-label">Agendamentos</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(34, 197, 94, 0.1); color: #22C55E;">
                    <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo $todayStats['confirmed']; ?></span>
                    <span class="stat-label">Confirmados</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(59, 130, 246, 0.1); color: #3B82F6;">
                    <iconify-icon icon="solar:check-read-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value"><?php echo $todayStats['completed']; ?></span>
                    <span class="stat-label">Finalizados</span>
                </div>
            </div>
            <div class="stat-card">
                <div class="stat-icon" style="background: rgba(168, 85, 247, 0.1); color: #A855F7;">
                    <iconify-icon icon="solar:wallet-money-bold"></iconify-icon>
                </div>
                <div class="stat-content">
                    <span class="stat-value">R$ <?php echo number_format($todayStats['revenue'], 0, ',', '.'); ?></span>
                    <span class="stat-label">Faturado</span>
                </div>
            </div>
        </div>
        
        <!-- Lista de Agendamentos -->
        <div class="agenda-grid">
            <?php if (empty($appointments)): ?>
            <div class="card empty-slot">
                <iconify-icon icon="solar:calendar-mark-bold" style="font-size: 3rem; margin-bottom: 1rem;"></iconify-icon>
                <h3>Nenhum agendamento</h3>
                <p>Não há agendamentos para <?php echo date('d/m/Y', strtotime($selectedDate)); ?></p>
                <button class="btn btn-primary" onclick="openAddModal()" style="margin-top: 1rem;">
                    <iconify-icon icon="solar:add-circle-bold"></iconify-icon>
                    Adicionar Agendamento
                </button>
            </div>
            <?php else: ?>
            
            <?php foreach ($appointments as $apt): ?>
            <div class="time-slot <?php echo $apt['status']; ?>">
                <div class="time-slot-time">
                    <iconify-icon icon="solar:clock-circle-bold"></iconify-icon>
                    <?php echo date('H:i', strtotime($apt['appointment_time'])); ?>
                </div>
                <div class="time-slot-content">
                    <div class="time-slot-client"><?php echo htmlspecialchars($apt['client_name']); ?></div>
                    <div class="time-slot-service"><?php echo htmlspecialchars($apt['service_name'] ?? 'Serviço não definido'); ?></div>
                    <div class="time-slot-meta">
                        <?php if ($apt['professional_name']): ?>
                        <div class="time-slot-meta-item">
                            <iconify-icon icon="solar:user-bold"></iconify-icon>
                            <?php echo htmlspecialchars($apt['professional_name']); ?>
                        </div>
                        <?php endif; ?>
                        <?php if ($apt['duration']): ?>
                        <div class="time-slot-meta-item">
                            <iconify-icon icon="solar:hourglass-bold"></iconify-icon>
                            <?php echo $apt['duration']; ?> min
                        </div>
                        <?php endif; ?>
                        <?php if ($apt['price']): ?>
                        <div class="time-slot-meta-item">
                            <iconify-icon icon="solar:wallet-bold"></iconify-icon>
                            R$ <?php echo number_format($apt['price'], 2, ',', '.'); ?>
                        </div>
                        <?php endif; ?>
                        <?php if ($apt['client_phone']): ?>
                        <div class="time-slot-meta-item">
                            <iconify-icon icon="solar:phone-bold"></iconify-icon>
                            <?php echo htmlspecialchars($apt['client_phone']); ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php if ($apt['notes']): ?>
                    <div style="margin-top: 0.5rem; font-size: 0.85rem; color: var(--text-muted);">
                        <em><?php echo htmlspecialchars($apt['notes']); ?></em>
                    </div>
                    <?php endif; ?>
                </div>
                <div class="time-slot-actions">
                    <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="status-select" onchange="this.form.submit()">
                            <option value="scheduled" <?php echo $apt['status'] === 'scheduled' ? 'selected' : ''; ?>>Agendado</option>
                            <option value="confirmed" <?php echo $apt['status'] === 'confirmed' ? 'selected' : ''; ?>>Confirmado</option>
                            <option value="completed" <?php echo $apt['status'] === 'completed' ? 'selected' : ''; ?>>Finalizado</option>
                            <option value="cancelled" <?php echo $apt['status'] === 'cancelled' ? 'selected' : ''; ?>>Cancelado</option>
                        </select>
                    </form>
                    <form method="POST" onsubmit="return confirm('Remover 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>
                </div>
            </div>
            <?php endforeach; ?>
            
            <?php endif; ?>
        </div>
    </main>
    
    <!-- Modal Adicionar -->
    <div id="appointmentModal" class="modal-overlay">
        <div class="modal-content card">
            <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="closeModal()" 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">
                <input type="hidden" name="date" value="<?php echo $selectedDate; ?>">
                
                <div class="form-grid-2">
                    <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="(00) 00000-0000">
                    </div>
                </div>
                
                <div class="form-grid-2">
                    <div class="form-group">
                        <label class="form-label">Serviço *</label>
                        <select name="service_id" class="form-input" required>
                            <option value="">Selecione</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="">Qualquer um disponível</option>
                            <?php foreach ($team as $member): ?>
                            <option value="<?php echo $member['id']; ?>"><?php echo htmlspecialchars($member['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Horário *</label>
                    <input type="time" name="time" class="form-input" required>
                </div>
                
                <div class="form-group">
                    <label class="form-label">Observações</label>
                    <textarea name="notes" class="form-input" rows="2" placeholder="Alguma observação..."></textarea>
                </div>
                
                <div style="display: flex; gap: 1rem; justify-content: flex-end; flex-wrap: wrap;">
                    <button type="button" class="btn btn-secondary" onclick="closeModal()">Cancelar</button>
                    <button type="submit" class="btn btn-primary">
                        <iconify-icon icon="solar:check-circle-bold"></iconify-icon>
                        Agendar
                    </button>
                </div>
            </form>
        </div>
    </div>

<script>
function openAddModal() {
    document.getElementById('appointmentModal').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

function closeModal() {
    document.getElementById('appointmentModal').style.display = 'none';
    document.body.style.overflow = '';
}

function changeDate(days) {
    const current = new Date(document.getElementById('dateSelector').value);
    current.setDate(current.getDate() + days);
    goToDate(current.toISOString().split('T')[0]);
}

function goToDate(date) {
    const url = new URL(window.location.href);
    url.searchParams.set('date', date);
    window.location.href = url.toString();
}

function filterByProfessional(id) {
    const url = new URL(window.location.href);
    if (id) {
        url.searchParams.set('professional', id);
    } else {
        url.searchParams.delete('professional');
    }
    window.location.href = url.toString();
}

document.getElementById('appointmentModal').addEventListener('click', function(e) {
    if (e.target === this) closeModal();
});

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeModal();
});
</script>

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