<?php
require_once __DIR__ . '/src/auth.php';
require_once __DIR__ . '/src/db.php';
require_once __DIR__ . '/src/history.php';
require_once __DIR__ . '/src/nextcloud.php';
require_once __DIR__ . '/src/contract_file_helper.php';
require_once __DIR__ . '/src/timeline_helper.php';
require_login();

$pdo = get_db_connection();
$id = $_GET['id'] ?? null;
if (!$id) {
    header('Location: contracts.php');
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM contracts WHERE id = ?");
$stmt->execute([$id]);
$contract = $stmt->fetch();

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

// Se o contrato estiver assinado ou finalizado, bloquear alterações se is_locked estiver ativo
$is_locked = (bool)($contract['is_locked'] ?? false);

$units = $pdo->query("SELECT * FROM units ORDER BY name ASC")->fetchAll();
$suppliers = $pdo->query("SELECT * FROM suppliers ORDER BY name ASC")->fetchAll();
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$is_locked) {
    // Handle status change for timeline
    $old_status = $contract['status'];
    
    $unit_id = $_POST['unit_id'];
    $contract_type = $_POST['contract_type'];
    $contract_number = $_POST['contract_number'];
    $supplier_id = $_POST['supplier_id'] ?: null;
    $title = $_POST['title'];
    $description = $_POST['description'];
    $observations = $_POST['observations'];
    $value = $_POST['value'];
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $alert_date = $_POST['alert_date'];
    $status = $_POST['status'];

    // Se o status mudou para 'Assinado' ou 'Finalizado', podemos trancar o contrato
    $new_is_locked = ($status === 'Assinado' || $status === 'Finalizado') ? 1 : 0;

    // Fetch supplier name for compatibility
    $supplier_name = '';
    if ($supplier_id) {
        $stmtS = $pdo->prepare("SELECT name FROM suppliers WHERE id = ?");
        $stmtS->execute([$supplier_id]);
        $supplier_name = $stmtS->fetchColumn();
    }

    $file_path = $contract['file_path']; // Keep the main file path for the latest version
    
    // Handle New Version Upload
    if (isset($_FILES['new_version_file']) && $_FILES['new_version_file']['error'] === UPLOAD_ERR_OK) {
        $originalName = basename($_FILES['new_version_file']['name']);
        $fileName = time() . '_' . $originalName;
        $tmpPath = $_FILES['new_version_file']['tmp_name'];
        
        // Buscar nome da unidade para a pasta
        $stmtUnit = $pdo->prepare("SELECT u.name FROM units u JOIN contracts c ON c.unit_id = u.id WHERE c.id = ?");
        $stmtUnit->execute([$id]);
        $unitName = $stmtUnit->fetchColumn();
        $unitFolder = $unitName ? preg_replace('/[\/:*?"<>|]/', '_', $unitName) : 'Geral';
        $destRemotePath = cfh_build_remote_contract_path($unitFolder, $fileName);

        // 1. Enviar para Nextcloud via WebDAV
        try {
            $nc = new Nextcloud();
            $remoteRoot = trim(str_replace('\\', '/', (string)cfh_get_remote_contracts_root()), '/');
            $parts = array_values(array_filter(explode('/', $remoteRoot), 'strlen'));
            $acc = '';
            foreach ($parts as $p) {
                $acc = $acc === '' ? $p : ($acc . '/' . $p);
                $nc->createFolder($acc);
            }
            $nc->createFolder($remoteRoot . '/' . $unitFolder);
            if ($nc->uploadFile($tmpPath, $destRemotePath)) {
                $new_file_path = $destRemotePath;
                
                // Atualizar o caminho principal na tabela contracts
                $stmtUpdateMain = $pdo->prepare("UPDATE contracts SET file_path = ? WHERE id = ?");
                $stmtUpdateMain->execute([$new_file_path, $id]);
                
                // Adicionar ao histórico de arquivos
                try {
                    $stmtAddHistory = $pdo->prepare("INSERT INTO contract_files (contract_id, file_path, is_amendment, username, user_id) VALUES (?, ?, 0, ?, ?)");
                    $stmtAddHistory->execute([$id, $new_file_path, $_SESSION['username'], $_SESSION['user_id']]);
                } catch (PDOException $e) {
                    $stmtAddHistory = $pdo->prepare("INSERT INTO contract_files (contract_id, file_path) VALUES (?, ?)");
                    $stmtAddHistory->execute([$id, $new_file_path]);
                }
                
                // Adicionar à timeline
                $msg_id = add_timeline_message($id, "Nova versão do contrato enviada: " . $originalName, 'system');
                add_timeline_attachment($id, $msg_id, $new_file_path, $originalName, 'application/pdf');

                log_contract_history($id, 'upload_new_version', ['file' => $new_file_path]);
                
                header("Location: edit_contract.php?id=$id&msg=version_uploaded");
                exit;
            }
        } catch (Exception $e) {
            $message = "Erro ao enviar para o Nextcloud: " . $e->getMessage();
        }
    }

    // Handle normal update
    if (isset($_POST['unit_id'])) {
        $stmtUpdate = $pdo->prepare("UPDATE contracts SET unit_id = ?, contract_type = ?, contract_number = ?, supplier_id = ?, supplier = ?, title = ?, description = ?, observations = ?, value = ?, start_date = ?, end_date = ?, alert_date = ?, status = ?, is_locked = ? WHERE id = ?");
        if ($stmtUpdate->execute([$unit_id, $contract_type, $contract_number, $supplier_id, $supplier_name, $title, $description, $observations, $value, $start_date, $end_date, $alert_date, $status, $new_is_locked, $id])) {
            
            // Log status change to timeline
            if ($old_status !== $status) {
                log_status_change($id, $old_status, $status);
            }

            log_contract_history($id, 'update', $_POST);
            header("Location: edit_contract.php?id=$id&msg=updated");
            exit;
        }
    }
}

// Handle message posting from timeline
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['timeline_message']) && !$is_locked) {
    $body = trim($_POST['timeline_message']);
    if ($body !== '') {
        add_timeline_message($id, $body, 'text', 'outgoing');
        header("Location: edit_contract.php?id=$id#timeline");
        exit;
    }
}

// Handle messages from redirect
if (isset($_GET['msg'])) {
    if ($_GET['msg'] === 'updated') $message = "Contrato atualizado com sucesso!";
    if ($_GET['msg'] === 'file_deleted') $message = "Arquivo excluído com sucesso!";
    if ($_GET['msg'] === 'version_uploaded') $message = "Nova versão do contrato enviada com sucesso!";
}

// Handle File Deletion (Should be outside POST check as it's a GET parameter)
if (isset($_GET['delete_file_id'])) {
    $file_id = $_GET['delete_file_id'];
    
    if ($file_id == 0) {
        // Caso especial: Deletar apenas a referência principal se for um arquivo legado
        $stmtUpdateMain = $pdo->prepare("UPDATE contracts SET file_path = NULL WHERE id = ?");
        $stmtUpdateMain->execute([$id]);
        log_contract_history($id, 'delete_legacy_file', ['file' => $contract['file_path']]);
        header("Location: edit_contract.php?id=$id&msg=file_deleted");
        exit;
    }
    
    // 1. Fetch file info to remove it from disk
    $stmtFile = $pdo->prepare("SELECT file_path FROM contract_files WHERE id = ? AND contract_id = ?");
    $stmtFile->execute([$file_id, $id]);
    $file_to_delete = $stmtFile->fetch();
    
    if ($file_to_delete) {
        $path = __DIR__ . '/' . $file_to_delete['file_path'];
        if (file_exists($path)) {
            unlink($path);
        }
        
        // 2. Remove from database
        $stmtDel = $pdo->prepare("DELETE FROM contract_files WHERE id = ?");
        $stmtDel->execute([$file_id]);
        
        // 3. If the deleted file was the main one, update contracts table to NULL or the next available file
        if ($file_to_delete['file_path'] === $contract['file_path']) {
            $stmtNext = $pdo->prepare("SELECT file_path FROM contract_files WHERE contract_id = ? ORDER BY uploaded_at DESC LIMIT 1");
            $stmtNext->execute([$id]);
            $next_file = $stmtNext->fetchColumn() ?: null;
            
            $stmtUpdateMain = $pdo->prepare("UPDATE contracts SET file_path = ? WHERE id = ?");
            $stmtUpdateMain->execute([$next_file, $id]);
        }
        
        log_contract_history($id, 'delete_file', ['file' => $file_to_delete['file_path']]);
        header("Location: edit_contract.php?id=$id&msg=file_deleted");
        exit;
    }
}

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

<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Editar Contrato</h2>
        <a href="contracts.php" class="btn btn-secondary">Voltar</a>
    </div>

    <?php if ($message): ?>
        <div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <?php if ($is_locked): ?>
        <div class="alert alert-warning">
            <i class="fas fa-lock me-2"></i> <strong>Contrato Bloqueado:</strong> Este contrato está assinado ou finalizado e não pode mais ser editado.
        </div>
    <?php endif; ?>

    <div class="row">
        <div class="col-lg-8">
            <div class="card mb-4">
                <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-file-contract me-2"></i> Informações do Contrato</h5>
                    <?php if ($is_locked): ?>
                        <span class="badge bg-light text-primary">BLOQUEADO</span>
                    <?php endif; ?>
                </div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data">
                        <fieldset <?= $is_locked ? 'disabled' : '' ?>>
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label>Unidade</label>
                                    <select name="unit_id" class="form-select" required>
                                        <?php foreach ($units as $unit): ?>
                                            <option value="<?= $unit['id'] ?>" <?= $unit['id'] == $contract['unit_id'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($unit['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label>Tipo de Contrato</label>
                                    <input type="text" name="contract_type" class="form-control" value="<?= htmlspecialchars($contract['contract_type'] ?? '') ?>" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label>Número do Contrato</label>
                                    <input type="text" name="contract_number" class="form-control" value="<?= htmlspecialchars($contract['contract_number'] ?? '') ?>" placeholder="Opcional">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label>Título</label>
                                    <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($contract['title']) ?>" required>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-12 mb-3">
                                    <label>Fornecedor</label>
                                    <select name="supplier_id" class="form-select" required>
                                        <option value="">Selecione...</option>
                                        <?php foreach ($suppliers as $s): ?>
                                            <option value="<?= $s['id'] ?>" <?= $s['id'] == $contract['supplier_id'] ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($s['name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label>Descrição</label>
                                <textarea name="description" class="form-control" rows="2"><?= htmlspecialchars($contract['description']) ?></textarea>
                            </div>
                            <div class="mb-3">
                                <label>Observações</label>
                                <textarea name="observations" class="form-control" rows="2"><?= htmlspecialchars($contract['observations'] ?? '') ?></textarea>
                            </div>

                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label>Valor (R$)</label>
                                    <input type="number" step="0.01" name="value" class="form-control" value="<?= htmlspecialchars($contract['value']) ?>">
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label>Status</label>
                                    <select name="status" class="form-select">
                                        <?php 
                                        $status_options = [
                                            'Recebido', 
                                            'Em negociação', 
                                            'Ajuste solicitado', 
                                            'Revisão interna', 
                                            'Aguardando assinatura', 
                                            'Assinado', 
                                            'Finalizado'
                                        ];
                                        foreach ($status_options as $opt): 
                                        ?>
                                            <option value="<?= $opt ?>" <?= $contract['status'] == $opt ? 'selected' : '' ?>><?= $opt ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label>Bloqueado para Edição</label>
                                    <div class="form-check form-switch mt-2">
                                        <input class="form-check-input" type="checkbox" name="is_locked" id="is_locked_switch" <?= $is_locked ? 'checked' : '' ?> disabled>
                                        <label class="form-check-label" for="is_locked_switch"><?= $is_locked ? 'Sim' : 'Não' ?></label>
                                    </div>
                                </div>
                            </div>
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label>Data Início</label>
                                    <input type="date" name="start_date" class="form-control" value="<?= htmlspecialchars($contract['start_date']) ?>" required>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label>Data Fim (Vencimento)</label>
                                    <input type="date" name="end_date" class="form-control" value="<?= htmlspecialchars($contract['end_date']) ?>" required>
                                </div>
                                <div class="col-md-4 mb-3">
                                    <label>Data Alerta</label>
                                    <input type="date" name="alert_date" class="form-control" value="<?= htmlspecialchars($contract['alert_date'] ?? '') ?>">
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary">Salvar Alterações</button>
                        </fieldset>
                    </form>
                </div>
            </div>

            <!-- Seção de Histórico de Arquivos -->
            <div class="card mb-4">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0"><i class="fas fa-file-pdf me-2"></i> Arquivos e Versões</h5>
                </div>
                <div class="card-body">
                    <form method="POST" enctype="multipart/form-data" class="mb-4 p-3 border rounded bg-light">
                        <fieldset <?= $is_locked ? 'disabled' : '' ?>>
                            <div class="mb-3">
                                <label for="new_version_file" class="form-label"><strong>Enviar Nova Versão (PDF)</strong></label>
                                <input type="file" name="new_version_file" class="form-control" accept=".pdf" required>
                            </div>
                            <button type="submit" class="btn btn-success"><i class="fas fa-upload me-2"></i> Enviar Nova Versão</button>
                        </fieldset>
                    </form>

                    <h6>Documentos Vinculados (Contrato e Aditivos):</h6>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle">
                            <thead class="table-light">
                                <tr>
                                    <th>Arquivo</th>
                                    <th>Data de Envio</th>
                                    <th>Ação</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                    try {
                                        $files_stmt = $pdo->prepare("SELECT * FROM contract_files WHERE contract_id = ? ORDER BY uploaded_at DESC");
                                        $files_stmt->execute([$id]);
                                        $files = $files_stmt->fetchAll();
                                        
                                        if (!empty($contract['file_path'])) {
                                            $main_file_exists_in_history = false;
                                            foreach ($files as $f) {
                                                if ($f['file_path'] === $contract['file_path']) {
                                                    $main_file_exists_in_history = true;
                                                    break;
                                                }
                                            }
                                            if (!$main_file_exists_in_history) {
                                                array_unshift($files, [
                                                    'id' => 0,
                                                    'file_path' => $contract['file_path'],
                                                    'uploaded_at' => $contract['created_at'] ?? date('Y-m-d H:i:s'),
                                                    'is_amendment' => 0,
                                                    'username' => 'Sistema'
                                                ]);
                                            }
                                        }
                                    } catch (PDOException $e) { $files = []; }
                                    
                                    foreach($files as $file):
                                ?>
                                <tr>
                                    <td>
                                        <div class="fw-bold"><?= basename($file['file_path']) ?></div>
                                        <?php if($file['file_path'] === $contract['file_path']): ?>
                                            <span class="badge bg-success small">Atual</span>
                                        <?php endif; ?>
                                    </td>
                                    <td><small><?= date('d/m/Y H:i', strtotime($file['uploaded_at'])) ?></small></td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="serve_file.php?path=<?= urlencode($file['file_path']) ?>" target="_blank" class="btn btn-sm btn-info"><i class="fas fa-eye"></i></a>
                                            <?php if (!$is_locked): ?>
                                            <a href="edit_contract.php?id=<?= $id ?>&delete_file_id=<?= $file['id'] ?>" 
                                               class="btn btn-sm btn-danger" 
                                               onclick="return confirm('Tem certeza?')">
                                                <i class="fas fa-trash"></i>
                                            </a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <!-- Timeline Estilo Chat -->
            <div class="card shadow-sm border-0" id="timeline">
                <div class="card-header bg-dark text-white">
                    <h5 class="mb-0"><i class="fas fa-comments me-2"></i> Timeline / Negociação</h5>
                </div>
                <div class="card-body p-0">
                    <div id="timeline-container" style="height: 500px; overflow-y: auto; background-color: #f8f9fa;" class="p-3">
                        <?php
                            $msg_stmt = $pdo->prepare("
                                SELECT m.*, a.file_path as att_path, a.file_name as att_name 
                                FROM contract_messages m
                                LEFT JOIN contract_attachments a ON m.id = a.message_id
                                WHERE m.contract_id = ? 
                                ORDER BY m.created_at ASC
                            ");
                            $msg_stmt->execute([$id]);
                            $messages = $msg_stmt->fetchAll();

                            if (empty($messages)):
                        ?>
                            <div class="text-center text-muted mt-5">
                                <i class="fas fa-history fa-3x mb-3"></i>
                                <p>Nenhuma atividade registrada ainda.</p>
                            </div>
                        <?php else: foreach($messages as $msg): ?>
                            <?php if ($msg['type'] === 'system' || $msg['type'] === 'status_change'): ?>
                                <div class="text-center my-3">
                                    <span class="badge bg-light text-muted border py-2 px-3 rounded-pill">
                                        <i class="fas <?= $msg['type'] === 'status_change' ? 'fa-exchange-alt' : 'fa-info-circle' ?> me-1"></i>
                                        <?= htmlspecialchars($msg['body']) ?>
                                        <small class="d-block mt-1"><?= date('d/m/Y H:i', strtotime($msg['created_at'])) ?></small>
                                    </span>
                                </div>
                            <?php else: ?>
                                <div class="mb-3 d-flex <?= $msg['direction'] === 'outgoing' ? 'justify-content-end' : 'justify-content-start' ?>">
                                    <div class="message-bubble p-3 rounded shadow-sm <?= $msg['direction'] === 'outgoing' ? 'bg-primary text-white' : 'bg-white border' ?>" style="max-width: 85%;">
                                        <div class="d-flex justify-content-between align-items-center mb-1">
                                            <small class="fw-bold"><?= htmlspecialchars($msg['username'] ?: ($msg['direction'] === 'outgoing' ? 'Você' : 'Remetente')) ?></small>
                                        </div>
                                        <div class="message-content">
                                            <?= nl2br(htmlspecialchars($msg['body'])) ?>
                                        </div>
                                        <?php if ($msg['att_path']): ?>
                                            <div class="mt-2 p-2 rounded bg-light text-dark small border d-flex align-items-center">
                                                <i class="fas fa-file-pdf text-danger me-2 fa-lg"></i>
                                                <div class="text-truncate" style="max-width: 150px;"><?= htmlspecialchars($msg['att_name']) ?></div>
                                                <a href="serve_file.php?path=<?= urlencode($msg['att_path']) ?>" target="_blank" class="ms-auto btn btn-xs btn-outline-primary py-0 px-1"><i class="fas fa-eye"></i></a>
                                            </div>
                                        <?php endif; ?>
                                        <div class="text-end mt-1">
                                            <small style="font-size: 0.7rem; opacity: 0.8;"><?= date('H:i', strtotime($msg['created_at'])) ?></small>
                                        </div>
                                    </div>
                                </div>
                            <?php endif; ?>
                        <?php endforeach; endif; ?>
                    </div>
                </div>
                <div class="card-footer bg-white border-top-0">
                    <form method="POST" id="timeline-form">
                        <fieldset <?= $is_locked ? 'disabled' : '' ?>>
                            <div class="input-group">
                                <textarea name="timeline_message" class="form-control" placeholder="Digite uma observação ou mensagem..." rows="1" required></textarea>
                                <button type="submit" class="btn btn-primary"><i class="fas fa-paper-plane"></i></button>
                            </div>
                        </fieldset>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<style>
    .message-bubble { position: relative; }
    #timeline-container::-webkit-scrollbar { width: 6px; }
    #timeline-container::-webkit-scrollbar-thumb { background-color: #ced4da; border-radius: 10px; }
</style>

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

    <!-- Histórico de Alterações -->
    <div class="card mt-4">
        <div class="card-header">
            <h5>Histórico de Alterações</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive" style="max-height: 200px;">
                <table class="table table-sm table-bordered">
                    <thead>
                        <tr>
                            <th>Data</th>
                            <th>Usuário</th>
                            <th>Ação</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                            $history_stmt = $pdo->prepare("SELECT * FROM contract_history WHERE contract_id = ? ORDER BY changed_at DESC");
                            $history_stmt->execute([$id]);
                            $history = $history_stmt->fetchAll();
                            foreach($history as $entry):
                        ?>
                        <tr>
                            <td><?= date('d/m/Y H:i', strtotime($entry['changed_at'])) ?></td>
                            <td><?= htmlspecialchars($entry['username']) ?></td>
                            <td><?= htmlspecialchars($entry['action']) ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

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