<?php
require_once __DIR__ . '/src/auth.php';
require_once __DIR__ . '/src/db.php';
require_login();

$pdo = get_db_connection();

// Filtros e Busca
$search = $_GET['search'] ?? '';
$status_filter = $_GET['status'] ?? '';
$priority_filter = $_GET['priority'] ?? '';

$sql = "SELECT * FROM email_contracts WHERE 1=1";
$params = [];

if ($search) {
    $sql .= " AND (company_name LIKE ? OR sender_email LIKE ? OR contract_number LIKE ? OR email_subject LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status_filter) {
    $sql .= " AND status = ?";
    $params[] = $status_filter;
}

if ($priority_filter) {
    $sql .= " AND priority = ?";
    $params[] = $priority_filter;
}

$sql .= " ORDER BY last_message_at DESC, created_at DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$contracts = $stmt->fetchAll();

// Contagem por status para o dashboard
$stats_stmt = $pdo->query("SELECT status, COUNT(*) as count FROM email_contracts GROUP BY status");
$stats = $stats_stmt->fetchAll(PDO::FETCH_KEY_PAIR);

require_once __DIR__ . '/templates/header.php';
?>

<div class="container-fluid py-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="fw-bold text-primary mb-0">Central de Negociação por E-mail</h2>
            <p class="text-muted">Gerencie seus contratos e conversas em um único lugar</p>
        </div>
        <div>
            <a href="settings.php" class="btn btn-outline-secondary me-2">
                <i class="fas fa-cog"></i> Configurações
            </a>
            <button class="btn btn-outline-primary me-2" onclick="refreshEmails(this)">
                <i class="fas fa-sync-alt"></i> Sincronizar E-mails
            </button>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#newContractModal">
                <i class="fas fa-plus"></i> Novo Processo Manual
            </button>
        </div>
    </div>

    <!-- Dashboard Stats -->
    <div class="row g-3 mb-4">
        <?php
        $status_cards = [
            'Recebido' => ['icon' => 'fa-inbox', 'color' => 'info'],
            'Em negociação' => ['icon' => 'fa-comments', 'color' => 'warning'],
            'Ajuste solicitado' => ['icon' => 'fa-edit', 'color' => 'danger'],
            'Revisão interna' => ['icon' => 'fa-search', 'color' => 'primary'],
            'Aguardando assinatura' => ['icon' => 'fa-signature', 'color' => 'info'],
            'Assinado' => ['icon' => 'fa-check-double', 'color' => 'success'],
            'Finalizado' => ['icon' => 'fa-archive', 'color' => 'secondary']
        ];

        foreach ($status_cards as $label => $config):
            $count = $stats[$label] ?? 0;
        ?>
            <div class="col-6 col-md-3 col-lg">
                <div class="card border-0 shadow-sm h-100">
                    <div class="card-body">
                        <div class="d-flex align-items-center">
                            <div class="flex-shrink-0 bg-<?= $config['color'] ?> bg-opacity-10 p-3 rounded">
                                <i class="fas <?= $config['icon'] ?> text-<?= $config['color'] ?> fa-lg"></i>
                            </div>
                            <div class="flex-grow-1 ms-3">
                                <h6 class="card-subtitle text-muted small text-uppercase fw-bold mb-1"><?= $label ?></h6>
                                <h4 class="card-title mb-0 fw-bold"><?= $count ?></h4>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- Filters and Search -->
    <div class="card border-0 shadow-sm mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3">
                <div class="col-md-5">
                    <div class="input-group">
                        <span class="input-group-text bg-white border-end-0"><i class="fas fa-search text-muted"></i></span>
                        <input type="text" name="search" class="form-control border-start-0" placeholder="Buscar por empresa, remetente, número ou assunto..." value="<?= htmlspecialchars($search) ?>">
                    </div>
                </div>
                <div class="col-md-2">
                    <select name="status" class="form-select">
                        <option value="">Todos os Status</option>
                        <?php foreach (array_keys($status_cards) as $label): ?>
                            <option value="<?= $label ?>" <?= $status_filter == $label ? 'selected' : '' ?>><?= $label ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <select name="priority" class="form-select">
                        <option value="">Todas Prioridades</option>
                        <option value="low" <?= $priority_filter == 'low' ? 'selected' : '' ?>>Baixa</option>
                        <option value="normal" <?= $priority_filter == 'normal' ? 'selected' : '' ?>>Normal</option>
                        <option value="high" <?= $priority_filter == 'high' ? 'selected' : '' ?>>Alta</option>
                        <option value="critical" <?= $priority_filter == 'critical' ? 'selected' : '' ?>>Crítica</option>
                    </select>
                </div>
                <div class="col-md-3 d-flex gap-2">
                    <button type="submit" class="btn btn-primary w-100">Filtrar</button>
                    <a href="email_contracts.php" class="btn btn-outline-secondary">Limpar</a>
                </div>
            </form>
        </div>
    </div>

    <?php if (empty($contracts)): ?>
        <?php
        $stmtS = $pdo->query("SELECT setting_value FROM system_settings WHERE setting_key = 'email_imap_host'");
        $imap_host = $stmtS->fetchColumn();
        if (empty($imap_host)):
        ?>
            <div class="col-12 text-center py-5">
                <i class="fas fa-exclamation-triangle fa-4x text-warning mb-3"></i>
                <h5>IMAP não configurado.</h5>
                <p class="text-muted">Configure as credenciais de e-mail em "Configurações" para começar a receber contratos.</p>
                <a href="settings.php" class="btn btn-primary">Configurar Agora</a>
            </div>
        <?php else: ?>
            <div class="col-12 text-center py-5">
                <i class="fas fa-folder-open fa-4x text-muted mb-3"></i>
                <h5>Nenhum processo de e-mail encontrado.</h5>
                <p class="text-muted">Sincronize seus e-mails ou inicie um processo manual.</p>
            </div>
        <?php endif; ?>
    <?php else: foreach ($contracts as $contract): 
            $status_config = $status_cards[$contract['status']] ?? ['color' => 'secondary', 'icon' => 'fa-question'];
            $priority_colors = ['low' => 'success', 'normal' => 'primary', 'high' => 'warning', 'critical' => 'danger'];
            $p_color = $priority_colors[$contract['priority']] ?? 'secondary';
        ?>
            <div class="col-md-6 col-xl-4">
                <div class="card h-100 border-0 shadow-sm hover-shadow transition-all <?= $contract['is_locked'] ? 'border-start border-success border-4' : '' ?>">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <span class="badge bg-<?= $status_config['color'] ?> bg-opacity-10 text-<?= $status_config['color'] ?> px-3 py-2 rounded-pill">
                                <i class="fas <?= $status_config['icon'] ?> me-1"></i> <?= $contract['status'] ?>
                            </span>
                            <span class="badge bg-<?= $p_color ?> bg-opacity-10 text-<?= $p_color ?>">
                                <?= ucfirst($contract['priority']) ?>
                            </span>
                        </div>
                        
                        <h5 class="card-title fw-bold mb-1 text-truncate"><?= htmlspecialchars($contract['company_name']) ?></h5>
                        <p class="text-muted small mb-3 text-truncate">
                            <i class="fas fa-envelope me-1"></i> <?= htmlspecialchars($contract['sender_email']) ?>
                        </p>
                        
                        <div class="bg-light p-3 rounded mb-3">
                            <div class="small text-muted mb-1">Assunto do E-mail:</div>
                            <div class="fw-bold small text-truncate"><?= htmlspecialchars($contract['email_subject'] ?: 'Sem assunto') ?></div>
                        </div>

                        <div class="row g-2 mb-3">
                            <div class="col-6">
                                <div class="small text-muted">Contrato Nº:</div>
                                <div class="fw-bold"><?= htmlspecialchars($contract['contract_number'] ?: '-') ?></div>
                            </div>
                            <div class="col-6">
                                <div class="small text-muted">Última Atividade:</div>
                                <div class="fw-bold"><?= $contract['last_message_at'] ? date('d/m/Y H:i', strtotime($contract['last_message_at'])) : '-' ?></div>
                            </div>
                        </div>

                        <?php if ($contract['is_locked']): ?>
                            <div class="alert alert-success py-2 px-3 small mb-3">
                                <i class="fas fa-check-circle me-1"></i> Contrato Principal Assinado
                            </div>
                        <?php endif; ?>
                    </div>
                    <div class="card-footer bg-white border-top-0 p-3">
                        <a href="email_contract_view.php?id=<?= $contract['id'] ?>" class="btn btn-outline-primary w-100 stretched-link">
                            <i class="fas fa-external-link-alt me-1"></i> Abrir Central de Negociação
                        </a>
                    </div>
                </div>
            </div>
        <?php endforeach; endif; ?>
    </div>
</div>

<!-- Modal Novo Processo Manual -->
<div class="modal fade" id="newContractModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">Iniciar Novo Processo de Contrato</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="email_contract_actions.php?action=create" method="POST" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Empresa/Fornecedor</label>
                        <input type="text" name="company_name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">E-mail do Contato</label>
                        <input type="email" name="sender_email" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Unidade</label>
                        <select name="unit_name" class="form-select" required>
                            <option value="">Selecione a unidade...</option>
                            <?php
                            $units = $pdo->query("SELECT name FROM units ORDER BY name ASC")->fetchAll(PDO::FETCH_COLUMN);
                            foreach ($units as $unit) echo "<option value=\"$unit\">$unit</option>";
                            ?>
                        </select>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Nº do Contrato</label>
                            <input type="text" name="contract_number" class="form-control">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">Prioridade</label>
                            <select name="priority" class="form-select">
                                <option value="low">Baixa</option>
                                <option value="normal" selected>Normal</option>
                                <option value="high">Alta</option>
                                <option value="critical">Crítica</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Contrato Inicial (PDF)</label>
                        <input type="file" name="contract_file" class="form-control" accept=".pdf" required>
                    </div>
                </div>
                <div class="modal-footer bg-light">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary px-4">Criar Processo</button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
    .transition-all { transition: all 0.3s ease; }
    .hover-shadow:hover { transform: translateY(-5px); box-shadow: 0 .5rem 1rem rgba(0,0,0,.15)!important; }
</style>

<script>
function refreshEmails(btn) {
    const icon = btn.querySelector('i');
    btn.disabled = true;
    icon.classList.add('fa-spin');
    
    fetch('email_contract_sync.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Sincronização concluída! ' + data.new_messages + ' novas mensagens encontradas.');
                window.location.reload();
            } else {
                alert('Erro na sincronização: ' + data.error);
            }
        })
        .catch(err => alert('Erro na requisição: ' + err))
        .finally(() => {
            btn.disabled = false;
            icon.classList.remove('fa-spin');
        });
}
</script>

<?php require_once __DIR__ . '/templates/footer.php'; ?>
