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

$pdo = get_db_connection();
$id = $_GET['id'] ?? null;

if (!$id) {
    header('Location: email_contracts.php');
    exit;
}

// Buscar dados do contrato
$stmt = $pdo->prepare("SELECT * FROM email_contracts WHERE id = ?");
$stmt->execute([$id]);
$contract = $stmt->fetch();

if (!$contract) {
    die("Processo de contrato não encontrado.");
}

$is_locked = (bool)$contract['is_locked'];

// Buscar mensagens da timeline
$msg_stmt = $pdo->prepare("
    SELECT * FROM email_contract_messages 
    WHERE contract_id = ? 
    ORDER BY sent_at ASC, created_at ASC
");
$msg_stmt->execute([$id]);
$messages = $msg_stmt->fetchAll();

// Buscar versões do contrato
$version_stmt = $pdo->prepare("
    SELECT * FROM email_contract_versions 
    WHERE contract_id = ? 
    ORDER BY version_number DESC
");
$version_stmt->execute([$id]);
$versions = $version_stmt->fetchAll();

// Buscar anexos gerais
$att_stmt = $pdo->prepare("
    SELECT * FROM email_contract_attachments 
    WHERE contract_id = ? 
    ORDER BY created_at DESC
");
$att_stmt->execute([$id]);
$attachments = $att_stmt->fetchAll();

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

<div class="container-fluid py-4 bg-light min-vh-100">
    <!-- Top Bar -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div class="d-flex align-items-center">
            <a href="email_contracts.php" class="btn btn-outline-secondary me-3">
                <i class="fas fa-arrow-left"></i>
            </a>
            <div>
                <h3 class="fw-bold mb-0"><?= htmlspecialchars($contract['company_name']) ?></h3>
                <div class="d-flex gap-2 mt-1">
                    <span class="badge bg-primary bg-opacity-10 text-primary">#<?= htmlspecialchars($contract['contract_number'] ?: $contract['id']) ?></span>
                    <span class="badge bg-secondary bg-opacity-10 text-secondary"><?= htmlspecialchars($contract['unit_name']) ?></span>
                    <span class="badge bg-info bg-opacity-10 text-info"><?= htmlspecialchars($contract['status']) ?></span>
                </div>
            </div>
        </div>
        <div class="d-flex gap-2">
            <?php if (!$is_locked): ?>
                <div class="dropdown">
                    <button class="btn btn-warning dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <i class="fas fa-tasks me-1"></i> Alterar Status
                    </button>
                    <ul class="dropdown-menu">
                        <?php
                        $statuses = ['Recebido', 'Em negociação', 'Ajuste solicitado', 'Revisão interna', 'Aguardando assinatura', 'Assinado', 'Finalizado'];
                        foreach ($statuses as $s):
                        ?>
                            <li><a class="dropdown-item" href="email_contract_actions.php?action=update_status&id=<?= $id ?>&status=<?= urlencode($s) ?>"><?= $s ?></a></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            <?php else: ?>
                <span class="btn btn-success disabled"><i class="fas fa-check-circle me-1"></i> Contrato Finalizado</span>
            <?php endif; ?>
            <a href="email_contract_actions.php?action=delete&id=<?= $id ?>" class="btn btn-outline-danger" onclick="return confirm('Tem certeza que deseja excluir todo este processo? Esta ação não pode ser desfeita.')">
                <i class="fas fa-trash"></i>
            </a>
        </div>
    </div>

    <div class="row g-4">
        <!-- Left Column: Timeline/Chat -->
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm h-100 d-flex flex-column" style="max-height: 80vh;">
                <div class="card-header bg-white border-bottom py-3 d-flex justify-content-between align-items-center">
                    <h5 class="mb-0 fw-bold text-dark"><i class="fas fa-comments text-primary me-2"></i> Timeline de Negociação</h5>
                    <div class="small text-muted"><?= count($messages) ?> mensagens registradas</div>
                </div>
                
                <div class="card-body overflow-auto p-4 bg-light" id="timeline-body">
                    <?php if (empty($messages)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-envelope-open text-muted fa-3x mb-3"></i>
                            <p class="text-muted">Aguardando primeira mensagem...</p>
                        </div>
                    <?php else: foreach ($messages as $msg): 
                        $is_outgoing = ($msg['direction'] === 'outgoing');
                    ?>
                        <div class="d-flex <?= $is_outgoing ? 'justify-content-end' : 'justify-content-start' ?> mb-4">
                            <div class="message-bubble <?= $is_outgoing ? 'bg-primary text-white shadow-primary' : 'bg-white border text-dark shadow-sm' ?> p-3 rounded-4" style="max-width: 80%;">
                                <div class="d-flex justify-content-between align-items-center mb-2">
                                    <span class="small fw-bold"><?= htmlspecialchars($msg['sender_name'] ?: ($is_outgoing ? 'Você' : 'Remetente')) ?></span>
                                    <span class="small opacity-75 ms-3">
                                        <?= date('d/m H:i', strtotime($msg['sent_at'] ?: $msg['created_at'])) ?>
                                        <a href="email_contract_actions.php?action=delete_message&id=<?= $id ?>&msg_id=<?= $msg['id'] ?>" class="<?= $is_outgoing ? 'text-white-50' : 'text-muted' ?> ms-2" onclick="return confirm('Excluir esta mensagem e seus anexos?')">
                                            <i class="fas fa-trash"></i>
                                        </a>
                                    </span>
                                </div>
                                <div class="message-text mb-2">
                                    <?= nl2br(htmlspecialchars($msg['body_text'] ?: strip_tags($msg['body_html']))) ?>
                                </div>
                                
                                <!-- Message Attachments -->
                                <?php
                                $msg_atts_stmt = $pdo->prepare("SELECT * FROM email_contract_attachments WHERE message_id = ?");
                                $msg_atts_stmt->execute([$msg['id']]);
                                $msg_atts = $msg_atts_stmt->fetchAll();
                                if (!empty($msg_atts)):
                                ?>
                                    <div class="mt-3 border-top pt-2 opacity-100">
                                        <div class="small fw-bold mb-2 <?= $is_outgoing ? 'text-white-50' : 'text-muted' ?>">Anexos:</div>
                                        <div class="d-flex flex-wrap gap-2">
                                            <?php foreach ($msg_atts as $att): ?>
                                                <a href="serve_file.php?path=<?= urlencode($att['stored_path']) ?>" target="_blank" class="btn btn-sm <?= $is_outgoing ? 'btn-light' : 'btn-outline-primary' ?> d-flex align-items-center py-1">
                                                    <i class="fas fa-file-pdf me-2"></i>
                                                    <span class="text-truncate" style="max-width: 150px;"><?= htmlspecialchars($att['original_name']) ?></span>
                                                </a>
                                            <?php endforeach; ?>
                                        </div>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; endif; ?>
                </div>

                <div class="card-footer bg-white border-top p-3">
                    <?php if (!$is_locked): ?>
                        <div id="drop-zone" class="mb-2 p-3 border-2 border-dashed rounded-4 text-center text-muted small d-none">
                            <i class="fas fa-cloud-upload-alt fa-2x mb-2"></i>
                            <div>Solte os arquivos para anexar à resposta</div>
                        </div>
                        <form action="email_contract_actions.php?action=send_message&id=<?= $id ?>" method="POST" enctype="multipart/form-data" id="replyForm">
                            <div class="mb-3">
                                <textarea name="message_body" id="message_body" class="form-control bg-light border-0" rows="3" placeholder="Escreva sua resposta aqui..." required></textarea>
                            </div>
                            <div class="d-flex justify-content-between align-items-center">
                                <div class="d-flex gap-2">
                                    <div class="file-upload-wrapper">
                                        <label class="btn btn-outline-secondary btn-sm" title="Anexar arquivos">
                                            <i class="fas fa-paperclip"></i>
                                            <input type="file" name="attachments[]" multiple style="display: none;" onchange="updateFileLabel(this)">
                                        </label>
                                    </div>
                                    <span id="file-count-label" class="small text-muted align-self-center"></span>
                                </div>
                                <div class="d-flex gap-2">
                                    <div class="form-check form-check-inline align-self-center">
                                        <input class="form-check-input" type="checkbox" name="is_new_version" id="is_new_version">
                                        <label class="form-check-label small" for="is_new_version">Marcar anexo como Nova Versão</label>
                                    </div>
                                    <button type="submit" class="btn btn-primary px-4">
                                        <i class="fas fa-paper-plane me-2"></i> Enviar E-mail
                                    </button>
                                </div>
                            </div>
                        </form>
                    <?php else: ?>
                        <div class="text-center py-2 text-muted italic">
                            <i class="fas fa-lock me-1"></i> Este processo está finalizado e não aceita novas mensagens.
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Right Column: Info & Versions -->
        <div class="col-lg-4">
            <!-- Versions Card -->
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold"><i class="fas fa-copy text-success me-2"></i> Controle de Versões</h5>
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush">
                        <?php if (empty($versions)): ?>
                            <div class="p-4 text-center text-muted">Nenhuma versão do contrato registrada.</div>
                        <?php else: foreach ($versions as $v): ?>
                            <div class="list-group-item p-3 border-0 border-bottom">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <div>
                                        <span class="badge bg-<?= ($v['version_label'] === 'final') ? 'success' : 'secondary' ?> mb-1">
                                            <?= strtoupper($v['version_label'] ?: 'V'.$v['version_number']) ?>
                                        </span>
                                        <h6 class="mb-0 fw-bold text-truncate" style="max-width: 200px;"><?= htmlspecialchars($v['file_name']) ?></h6>
                                    </div>
                                    <div class="btn-group">
                                        <a href="serve_file.php?path=<?= urlencode($v['file_path']) ?>" target="_blank" class="btn btn-sm btn-outline-primary" title="Ver PDF"><i class="fas fa-eye"></i></a>
                                        <a href="serve_file.php?path=<?= urlencode($v['file_path']) ?>" download class="btn btn-sm btn-outline-secondary" title="Baixar"><i class="fas fa-download"></i></a>
                                    </div>
                                </div>
                                <div class="small text-muted">
                                    <i class="fas fa-calendar-alt me-1"></i> <?= date('d/m/Y H:i', strtotime($v['created_at'])) ?>
                                </div>
                            </div>
                        <?php endforeach; endif; ?>
                    </div>
                </div>
                <?php if (!$is_locked): ?>
                    <div class="card-footer bg-white p-3">
                        <button class="btn btn-outline-success w-100 btn-sm" data-bs-toggle="modal" data-bs-target="#uploadVersionModal">
                            <i class="fas fa-upload me-1"></i> Upload Manual de Nova Versão
                        </button>
                    </div>
                <?php endif; ?>
            </div>

            <!-- Audit Log -->
            <div class="card border-0 shadow-sm">
                <div class="card-header bg-white border-bottom py-3">
                    <h5 class="mb-0 fw-bold"><i class="fas fa-history text-muted me-2"></i> Auditoria</h5>
                </div>
                <div class="card-body p-0">
                    <div class="list-group list-group-flush overflow-auto" style="max-height: 300px;">
                        <?php
                        $audit_stmt = $pdo->prepare("SELECT * FROM email_contract_history WHERE contract_id = ? ORDER BY created_at DESC");
                        $audit_stmt->execute([$id]);
                        $audits = $audit_stmt->fetchAll();
                        if (empty($audits)):
                        ?>
                            <div class="p-4 text-center text-muted small">Nenhum registro de auditoria.</div>
                        <?php else: foreach ($audits as $log): ?>
                            <div class="list-group-item p-3 border-0 border-bottom small">
                                <div class="fw-bold mb-1"><?= htmlspecialchars($log['action_type']) ?></div>
                                <div class="text-muted mb-1"><?= htmlspecialchars($log['description']) ?></div>
                                <div class="text-muted" style="font-size: 0.75rem;">
                                    <?= date('d/m/Y H:i', strtotime($log['created_at'])) ?>
                                </div>
                            </div>
                        <?php endforeach; endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Modal Upload Version -->
<div class="modal fade" id="uploadVersionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content border-0 shadow">
            <div class="modal-header bg-success text-white">
                <h5 class="modal-title">Fazer Upload de Nova Versão</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form action="email_contract_actions.php?action=upload_version&id=<?= $id ?>" method="POST" enctype="multipart/form-data">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label fw-bold">Arquivo PDF</label>
                        <input type="file" name="contract_file" class="form-control" accept=".pdf" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label fw-bold">Rótulo da Versão</label>
                        <select name="version_label" class="form-select">
                            <option value="">Automático (vX)</option>
                            <option value="v1">Versão 1</option>
                            <option value="v2">Versão 2</option>
                            <option value="final">Versão Final</option>
                        </select>
                    </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-success px-4">Salvar Versão</button>
                </div>
            </form>
        </div>
    </div>
</div>

<style>
    .message-bubble { border-radius: 1.25rem; }
    .shadow-primary { box-shadow: 0 4px 15px rgba(13, 110, 253, 0.2); }
    #timeline-body::-webkit-scrollbar { width: 6px; }
    #timeline-body::-webkit-scrollbar-thumb { background-color: #dee2e6; border-radius: 10px; }
    .btn-xs { padding: 0.1rem 0.25rem; font-size: 0.75rem; }
    .border-dashed { border-style: dashed !important; border-color: #dee2e6 !important; }
    #drop-zone.dragover { background-color: #e9ecef; border-color: #0d6efd !important; color: #0d6efd !important; }
</style>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const container = document.getElementById('timeline-body');
        container.scrollTop = container.scrollHeight;

        // Drag & Drop Logic
        const dropZone = document.getElementById('drop-zone');
        const replyForm = document.getElementById('replyForm');
        const fileInput = replyForm.querySelector('input[type="file"]');
        const timelineBody = document.getElementById('timeline-body');

        if (dropZone) {
            window.addEventListener('dragenter', (e) => {
                e.preventDefault();
                dropZone.classList.remove('d-none');
            });

            dropZone.addEventListener('dragover', (e) => {
                e.preventDefault();
                dropZone.classList.add('dragover');
            });

            dropZone.addEventListener('dragleave', (e) => {
                e.preventDefault();
                dropZone.classList.remove('dragover');
                // Check if leaving to outside window
                if (e.relatedTarget === null) {
                    dropZone.classList.add('d-none');
                }
            });

            dropZone.addEventListener('drop', (e) => {
                e.preventDefault();
                dropZone.classList.remove('dragover');
                dropZone.classList.add('d-none');
                
                if (e.dataTransfer.files.length > 0) {
                    fileInput.files = e.dataTransfer.files;
                    updateFileLabel(fileInput);
                }
            });
        }
    });

    function updateFileLabel(input) {
        const label = document.getElementById('file-count-label');
        if (input.files.length > 0) {
            label.textContent = input.files.length + (input.files.length === 1 ? ' arquivo selecionado' : ' arquivos selecionados');
        } else {
            label.textContent = '';
        }
    }
</script>

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