<?php
require_once __DIR__ . '/src/nextcloud.php';
require_once __DIR__ . '/src/auth.php';
require_once __DIR__ . '/src/db.php';
require_once __DIR__ . '/src/history.php';
require_once __DIR__ . '/src/contract_file_helper.php';

require_login();
$pdo = get_db_connection();

// Gerar token temporário para visualização de arquivos (bypass de sessão em novas abas)
try {
    $admin_token = bin2hex(random_bytes(16));
    $token_expires = date('Y-m-d H:i:s', strtotime('+1 hour'));
    $stmt_token = $pdo->prepare("UPDATE users SET temp_token = ?, token_expires = ? WHERE id = ?");
    $stmt_token->execute([$admin_token, $token_expires, $_SESSION['user_id']]);
    $user_id = $_SESSION['user_id'];
} catch (Exception $e) {
    $admin_token = '';
    $user_id = $_SESSION['user_id'] ?? 0;
}

$message = '';

// Handle Create Contract
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create') {
    $unit_id = $_POST['unit_id'];
    $contract_type = $_POST['contract_type'];
    $contract_number = $_POST['contract_number'];
    $supplier_id = $_POST['supplier_id'] ?: null; // Use supplier_id instead of supplier string
    $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'];


    $supplier_name = '';
    if ($supplier_id) {
        $stmtS = $pdo->prepare("SELECT name FROM suppliers WHERE id = ?");
        $stmtS->execute([$supplier_id]);
        $supplier_name = $stmtS->fetchColumn();
    }
    
    // File Upload (PDF)
    $file_path = null;
    $orphan_file_path = $_POST['orphan_file_path'] ?? null;
    $orphan_full_path = $_POST['orphan_full_path'] ?? null;
    $orphan_source = $_POST['orphan_source'] ?? null;
    $backup_file_path = '';

    if ($orphan_file_path) {
        // Se estamos criando a partir de um órfão, o arquivo já existe
        $fileName = basename(urldecode($orphan_file_path));

        $finalRemotePath = urldecode($orphan_file_path);
        $finalLocalPath = $orphan_full_path ? urldecode($orphan_full_path) : null;

        try {
            $nc = new Nextcloud();
            
            // Buscar nome da unidade para organizar a pasta
            $stmtUnit = $pdo->prepare("SELECT name FROM units WHERE id = ?");
            $stmtUnit->execute([$unit_id]);
            $unitName = $stmtUnit->fetchColumn();
            if ($unitName) {
                $organized = cfh_organize_contract_file($nc, $orphan_source, $finalRemotePath, $finalLocalPath, $unitName, $fileName);
                $finalRemotePath = $organized['remote_path'];
                $finalLocalPath = $organized['full_path'];
                $backup_file_path = $organized['backup_path'];
            }
            $file_path = $finalRemotePath;
        } catch (Exception $e) { /* erro */ }
    } else if (isset($_FILES['contract_file']) && $_FILES['contract_file']['error'] === UPLOAD_ERR_OK) {
        // Upload de um novo arquivo direto do computador
        $originalName = basename($_FILES['contract_file']['name']);
        $fileName = time() . '_' . $originalName;
        $tmpPath = $_FILES['contract_file']['tmp_name'];
        
        // Buscar nome da unidade para a pasta
        $stmtUnit = $pdo->prepare("SELECT name FROM units WHERE id = ?");
        $stmtUnit->execute([$unit_id]);
        $unitName = $stmtUnit->fetchColumn();
        $unitFolder = $unitName ? preg_replace('/[\/:*?"<>|]/', '_', $unitName) : 'Geral';
        $destRemotePath = cfh_build_remote_contract_path($unitFolder, $fileName);

        // Enviar direto para o 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)) {
                $file_path = $destRemotePath;
            }
            $backup_file_path = cfh_backup_from_local($tmpPath, $destRemotePath, $fileName);
        } catch (Exception $e) {
            // Log erro mas continua
        }
    }

    if ($file_path && $backup_file_path === '') {
        try {
            $ncBackup = isset($nc) && $nc instanceof Nextcloud ? $nc : new Nextcloud();
            $backup_file_path = cfh_backup_from_remote($ncBackup, $file_path, basename($file_path));
        } catch (Exception $e) {
            $backup_file_path = '';
        }
    }

    $stmt = $pdo->prepare("INSERT INTO contracts (unit_id, contract_type, contract_number, supplier_id, supplier, title, description, observations, value, start_date, end_date, alert_date, status, file_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    if ($stmt->execute([$unit_id, $contract_type, $contract_number, $supplier_id, $supplier_name, $title, $description, $observations, $value, $start_date, $end_date, $alert_date, $status, $file_path])) {
        $contract_id = $pdo->lastInsertId();
        
        // Save the first file version to the history table
        if ($file_path) {
            try {
                $stmtFile = $pdo->prepare("INSERT INTO contract_files (contract_id, file_path, is_amendment) VALUES (?, ?, 0)");
                $stmtFile->execute([
                    $contract_id, 
                    $file_path
                ]);
            } catch (PDOException $e) {
                // Silenciar se a tabela ou coluna não existir ainda
            }
        }
        
        $historyData = $_POST;
        if ($file_path) {
            $historyData['file_path'] = $file_path;
        }
        if ($backup_file_path) {
            $historyData['backup_file'] = $backup_file_path;
        }
        log_contract_history($contract_id, 'create', $historyData);
        header("Location: contracts.php?msg=created");
        exit;
    } else {
        $message = "Erro ao criar contrato.";
    }
}

// Handle Delete Signature Link
if (isset($_GET['delete_link'])) {
    $link_id = $_GET['delete_link'];
    $contract_id = $_GET['id'];
    $stmt = $pdo->prepare("DELETE FROM contract_signatures WHERE id = ?");
    $stmt->execute([$link_id]);
    header("Location: contracts.php?msg=link_deleted");
    exit;
}

// Handle messages from redirect
if (isset($_GET['msg'])) {
    if ($_GET['msg'] === 'created') $message = "Contrato criado com sucesso!";
    if ($_GET['msg'] === 'deleted') $message = "Contrato excluído com sucesso!";
    if ($_GET['msg'] === 'link_deleted') $message = "Link de assinatura excluído com sucesso!";
}

// Handle Delete
if (isset($_GET['delete'])) {
    $stmt = $pdo->prepare("DELETE FROM contracts WHERE id = ?");
    $stmt->execute([$_GET['delete']]);
    header("Location: contracts.php?msg=deleted");
    exit;
}

// Filtering
$filter_unit = $_GET['unit_id'] ?? '';
$filter_status = $_GET['status'] ?? '';
$search_term = $_GET['search'] ?? '';
$end_date_filter = $_GET['end_date_filter'] ?? '';

$sql = "SELECT c.*, u.name as unit_name, s.name as supplier_name, s.phone as supplier_phone,
         COALESCE(amend.count, 0) as amendment_count
         FROM contracts c 
         LEFT JOIN units u ON c.unit_id = u.id 
         LEFT JOIN suppliers s ON c.supplier_id = s.id
         LEFT JOIN (
            SELECT contract_id, COUNT(*) as count 
            FROM contract_files 
            WHERE is_amendment = 1 OR file_path LIKE 'Aditivo_%' OR file_path LIKE '%/Aditivo_%'
            GROUP BY contract_id
         ) amend ON c.id = amend.contract_id";
$where = [];
$params = [];

if ($filter_unit) {
    $where[] = "c.unit_id = ?";
    $params[] = $filter_unit;
}
if ($filter_status) {
    if ($filter_status === 'expired') {
        $where[] = "c.end_date < CURDATE() AND c.status NOT IN ('completed', 'canceled')";
    } else {
        $where[] = "c.status = ?";
        $params[] = $filter_status;
    }
}
if ($search_term) {
    $where[] = "(c.title LIKE ? OR c.contract_number LIKE ? OR c.supplier LIKE ?)";
    $params[] = "%$search_term%";
    $params[] = "%$search_term%";
    $params[] = "%$search_term%";
}
if ($end_date_filter) {
    $where[] = "c.end_date = ?";
    $params[] = $end_date_filter;
}

if (!empty($where)) {
    $sql .= " WHERE " . implode(" AND ", $where);
}

$sql .= " ORDER BY c.created_at DESC";

$stmt = $pdo->prepare($sql);
try {
    $stmt->execute($params);
    $contracts = $stmt->fetchAll();
} catch (PDOException $e) {
    // Fallback se a coluna is_amendment ainda não existir
    $sql_fallback = "SELECT c.*, u.name as unit_name, s.name as supplier_name, s.phone as supplier_phone,
                     COALESCE(amend.count, 0) as amendment_count
                     FROM contracts c 
                     JOIN units u ON c.unit_id = u.id 
                     LEFT JOIN suppliers s ON c.supplier_id = s.id
                     LEFT JOIN (
                        SELECT contract_id, COUNT(*) as count 
                        FROM contract_files 
                        WHERE file_path LIKE 'Aditivo_%' OR file_path LIKE '%/Aditivo_%'
                        GROUP BY contract_id
                     ) amend ON c.id = amend.contract_id";
    if (!empty($where)) {
        $sql_fallback .= " WHERE " . implode(" AND ", $where);
    }
    $sql_fallback .= " ORDER BY c.created_at DESC";
    $stmt = $pdo->prepare($sql_fallback);
    $stmt->execute($params);
    $contracts = $stmt->fetchAll();
}

try {
    $all_units = $pdo->query("SELECT * FROM units ORDER BY name ASC")->fetchAll();
    $units = $all_units; // For the modal
    $all_suppliers = $pdo->query("SELECT * FROM suppliers ORDER BY name ASC")->fetchAll();
} catch (PDOException $e) {
    $all_units = [];
    $units = [];
    $all_suppliers = [];
}

// Checar se estamos criando um contrato a partir de um arquivo órfão
$is_creating_from_orphan = ($_GET['action'] ?? '') === 'create_from_orphan';
$orphan_file_path = $is_creating_from_orphan ? $_GET['file_path'] : '';
$orphan_source = $is_creating_from_orphan ? $_GET['source'] : '';
$orphan_full_path = $is_creating_from_orphan ? ($_GET['full_path'] ?? '') : '';
$orphan_unit_id = $is_creating_from_orphan ? ($_GET['unit_id'] ?? '') : '';

?>

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

<script>
    // Abrir modal de novo contrato automaticamente se estiver criando a partir de um órfão
    document.addEventListener('DOMContentLoaded', function() {
        const urlParams = new URLSearchParams(window.location.search);
        if (urlParams.get('action') === 'create_from_orphan') {
            const addContractModal = new bootstrap.Modal(document.getElementById('addContractModal'));
            addContractModal.show();
        }
    });

    function refreshServerList(btn) {
        const icon = document.getElementById('refresh-icon');
        btn.disabled = true;
        icon.classList.add('fa-spin');
        const requestUrl = 'ajax_orphans_count.php?refresh=1&t=' + Date.now();

        fetch(requestUrl, { cache: 'no-store' })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Lista do servidor atualizada com sucesso! Foram encontrados ' + data.count + ' arquivos pendentes.');
                    // Se houver arquivos novos, talvez o usuário queira ir para o gerenciador
                    if (data.count > 0 && confirm('Existem arquivos pendentes. Deseja ir para o Gerenciador de Arquivos agora?')) {
                        window.location.href = 'sync_manager.php';
                    }
                } else {
                    alert('Erro ao atualizar lista: ' + (data.error || 'Erro desconhecido'));
                }
            })
            .catch(error => {
                console.error('Erro:', error);
                alert('Erro ao atualizar lista do servidor: ' + error.message);
            })
            .finally(() => {
                btn.disabled = false;
                icon.classList.remove('fa-spin');
            });
    }
</script>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Gerenciar Contratos</h2>
        <div>
            <button onclick="refreshServerList(this)" class="btn btn-outline-secondary me-2">
                <i class="fas fa-sync-alt" id="refresh-icon"></i> Atualizar Lista do Servidor
            </button>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addContractModal">
                <i class="fas fa-plus"></i> Novo Contrato
            </button>
        </div>
    </div>

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

    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger"><?= htmlspecialchars($_SESSION['error']) ?></div>
        <?php unset($_SESSION['error']); ?>
    <?php endif; ?>

    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label">Unidade</label>
                    <select name="unit_id" class="form-select">
                        <option value="">Todas</option>
                        <?php foreach ($all_units as $unit): ?>
                            <option value="<?= $unit['id'] ?>" <?= $filter_unit == $unit['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($unit['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="form-label">Status</label>
                    <select name="status" class="form-select">
                        <option value="">Todos</option>
                        <option value="Recebido" <?= $filter_status == 'Recebido' ? 'selected' : '' ?>>Recebido</option>
                        <option value="Em negociação" <?= $filter_status == 'Em negociação' ? 'selected' : '' ?>>Em negociação</option>
                        <option value="Ajuste solicitado" <?= $filter_status == 'Ajuste solicitado' ? 'selected' : '' ?>>Ajuste solicitado</option>
                        <option value="Revisão interna" <?= $filter_status == 'Revisão interna' ? 'selected' : '' ?>>Revisão interna</option>
                        <option value="Aguardando assinatura" <?= $filter_status == 'Aguardando assinatura' ? 'selected' : '' ?>>Aguardando assinatura</option>
                        <option value="Assinado" <?= $filter_status == 'Assinado' ? 'selected' : '' ?>>Assinado</option>
                        <option value="Finalizado" <?= $filter_status == 'Finalizado' ? 'selected' : '' ?>>Finalizado</option>
                        <option value="expired" <?= $filter_status == 'expired' ? 'selected' : '' ?>>Vencido</option>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">Pesquisar</label>
                    <input type="text" name="search" class="form-control" placeholder="Título, Nº Contrato, Fornecedor..." value="<?= htmlspecialchars($search_term) ?>">
                </div>
                <div class="col-md-2">
                    <label class="form-label">Data Fim</label>
                    <input type="date" name="end_date_filter" class="form-control" value="<?= htmlspecialchars($end_date_filter) ?>">
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary"><i class="fas fa-filter"></i> Filtrar</button>
                    <a href="contracts.php" class="btn btn-secondary">Limpar</a>
                </div>
            </form>
        </div>
    </div>

    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Título</th>
                            <th>Tipo</th>
                            <th>Nº Contrato</th>
                            <th>Fornecedor</th>
                            <th>Unidade</th>
                            <th>Aditivos</th>
                            <th>Valor</th>
                            <th>Status</th>
                            <th>Fim</th>
                            <th>Alerta</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($contracts as $contract): ?>
                        <?php 
                            $is_expired = strtotime($contract['end_date']) < time() && $contract['status'] !== 'completed' && $contract['status'] !== 'canceled';
                            $is_alert = $contract['alert_date'] && strtotime($contract['alert_date']) <= time() && !$is_expired && $contract['status'] === 'active';
                            $amendment_count = isset($contract['amendment_count']) ? (int)$contract['amendment_count'] : 0;
                            $has_amendment = $amendment_count > 0;
                            
                            $row_class = '';
                            if ($is_expired) {
                                $row_class = 'table-danger';
                            } elseif ($is_alert) {
                                $row_class = 'table-warning';
                            } elseif ($has_amendment) {
                                $row_class = 'table-info bg-opacity-10'; // Cor diferente para aditivos
                            }
                        ?>
                        <tr class="<?= $row_class ?>">
                            <td><?= htmlspecialchars($contract['title']) ?></td>
                            <td><?= htmlspecialchars($contract['contract_type'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($contract['contract_number'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($contract['supplier_name'] ?? $contract['supplier'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($contract['unit_name']) ?></td>
                            <td class="text-center">
                                <?php if ($has_amendment): ?>
                                    <span class="badge bg-info text-dark" title="Este contrato possui <?= $amendment_count ?> aditivo(s)">
                                        <i class="fas fa-file-signature me-1"></i> <?= $amendment_count ?>
                                    </span>
                                <?php else: ?>
                                    <span class="text-muted small">0</span>
                                <?php endif; ?>
                            </td>
                            <td>R$ <?= number_format((float)($contract['value'] ?? 0), 2, ',', '.') ?></td>
                            <td>
                                <?php if ($is_expired): ?>
                                    <span class="badge bg-danger">Vencido</span>
                                <?php else: ?>
                                    <?php
                                        $status_color = 'secondary';
                                        switch($contract['status']) {
                                            case 'Recebido': $status_color = 'info'; break;
                                            case 'Em negociação': $status_color = 'warning text-dark'; break;
                                            case 'Ajuste solicitado': $status_color = 'danger'; break;
                                            case 'Revisão interna': $status_color = 'primary'; break;
                                            case 'Aguardando assinatura': $status_color = 'info'; break;
                                            case 'Assinado': $status_color = 'success'; break;
                                            case 'Finalizado': $status_color = 'dark'; break;
                                        }
                                    ?>
                                    <span class="badge bg-<?= $status_color ?>">
                                        <?= htmlspecialchars($contract['status']) ?>
                                    </span>
                                <?php endif; ?>
                            </td>
                            <td><?= date('d/m/Y', strtotime($contract['end_date'])) ?></td>
                            <td><?= $contract['alert_date'] ? date('d/m/Y', strtotime($contract['alert_date'])) : '-' ?></td>
                            <td>
                                <button class="btn btn-sm btn-info" data-bs-toggle="modal" data-bs-target="#viewContractModal<?= $contract['id'] ?>"><i class="fas fa-eye"></i></button>
                                <a href="edit_contract.php?id=<?= $contract['id'] ?>" class="btn btn-sm btn-warning"><i class="fas fa-edit"></i></a>
                                <a href="contracts.php?delete=<?= $contract['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Tem certeza?')"><i class="fas fa-trash"></i></a>
                                <button class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#signModal<?= $contract['id'] ?>"><i class="fas fa-signature"></i></button>
                                <?php if ($contract['file_path']): ?>
                                    <a href="view_with_signature.php?path=<?= urlencode($contract['file_path']) ?>&contract_id=<?= $contract['id'] ?>&uid=<?= $user_id ?>&utoken=<?= $admin_token ?>" target="_blank" class="btn btn-sm btn-primary" title="Ver PDF com Selo de Assinatura"><i class="fas fa-file-pdf"></i></a>
                                    <a href="serve_file.php?path=<?= urlencode($contract['file_path']) ?>&uid=<?= $user_id ?>&utoken=<?= $admin_token ?>" target="_blank" class="btn btn-sm btn-outline-secondary" title="Baixar Original"><i class="fas fa-file-download"></i></a>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<?php foreach ($contracts as $contract): ?>
    <!-- Modal Assinatura -->
    <div class="modal fade" id="signModal<?= $contract['id'] ?>" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Assinatura Digital</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <p class="small text-muted mb-3">Escolha qual documento deve ser assinado:</p>
                    <form action="generate_signature_link.php" method="POST">
                        <input type="hidden" name="contract_id" value="<?= $contract['id'] ?>">
                        
                        <div class="list-group mb-3">
                            <!-- Contrato Principal -->
                            <?php if ($contract['file_path']): ?>
                                <label class="list-group-item d-flex align-items-center">
                                    <input class="form-check-input me-3" type="radio" name="file_path" value="<?= htmlspecialchars($contract['file_path']) ?>" checked required>
                                    <div>
                                        <div class="fw-bold">Contrato Principal</div>
                                        <div class="small text-muted"><?= basename($contract['file_path']) ?></div>
                                    </div>
                                </label>
                            <?php endif; ?>

                            <!-- Aditivos -->
                            <?php 
                                try {
                                    $aditivos_stmt = $pdo->prepare("SELECT file_path, observations, uploaded_at FROM contract_files WHERE contract_id = ? AND is_amendment = 1 ORDER BY uploaded_at DESC");
                                    $aditivos_stmt->execute([$contract['id']]);
                                    $aditivos_list = $aditivos_stmt->fetchAll();
                                    foreach ($aditivos_list as $ad):
                                ?>
                                    <label class="list-group-item d-flex align-items-center">
                                        <input class="form-check-input me-3" type="radio" name="file_path" value="<?= htmlspecialchars($ad['file_path']) ?>" required>
                                        <div>
                                            <div class="fw-bold text-warning">Aditivo (<?= date('d/m/Y', strtotime($ad['uploaded_at'])) ?>)</div>
                                            <div class="small text-muted"><?= htmlspecialchars($ad['observations'] ?: basename($ad['file_path'])) ?></div>
                                        </div>
                                    </label>
                                <?php 
                                    endforeach;
                                } catch (PDOException $e) {} 
                            ?>
                        </div>

                        <div class="d-grid">
                            <button type="submit" class="btn btn-primary"><i class="fas fa-link me-1"></i> Gerar Link de Assinatura</button>
                        </div>
                    </form>
                    <hr>
                    <h6>Links Gerados:</h6>
                    <?php 
                        try {
                            $links_stmt = $pdo->prepare("SELECT * FROM contract_signatures WHERE contract_id = ? ORDER BY created_at DESC");
                            $links_stmt->execute([$contract['id']]);
                            $links = $links_stmt->fetchAll();
                        } catch (PDOException $e) {
                            $links = [];
                        }
                        foreach($links as $link): 
                    ?>
                        <div class="input-group mb-2">
                            <input type="text" class="form-control form-control-sm" value="<?= APP_URL . '/sign.php?token=' . $link['token'] ?>" readonly id="sign-link-<?= $link['id'] ?>">
                            <button class="btn btn-sm btn-outline-secondary" type="button" onclick="copyToClipboard('#sign-link-<?= $link['id'] ?>')" title="Copiar Link"><i class="fas fa-copy"></i></button>
                            <button class="btn btn-sm btn-outline-success" type="button" 
                                    onclick="openWhatsAppModal('<?= $link['id'] ?>', '<?= addslashes("Olá! Segue o link para assinatura do contrato: " . APP_URL . '/sign.php?token=' . $link['token']) ?>', '<?= preg_replace('/\D/', '', (string)($contract['supplier_phone'] ?? '')) ?>')" title="Enviar WhatsApp">
                                <i class="fab fa-whatsapp"></i>
                            </button>
                            <a href="contracts.php?delete_link=<?= $link['id'] ?>&id=<?= $contract['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Excluir este link de assinatura?')" title="Excluir Link">
                                <i class="fas fa-trash"></i>
                            </a>
                            <span class="input-group-text p-1">
                                <?php if($link['is_signed']): ?>
                                    <i class="fas fa-check-circle text-success" title="Assinado"></i>
                                <?php else: ?>
                                    <i class="fas fa-clock text-warning" title="Pendente"></i>
                                <?php endif; ?>
                            </span>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal Ver Detalhes -->
    <div class="modal fade" id="viewContractModal<?= $contract['id'] ?>" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title"><?= htmlspecialchars($contract['title']) ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="row mb-3">
                            <div class="col-md-4"><strong>Tipo:</strong><br><?= htmlspecialchars($contract['contract_type'] ?? '-') ?></div>
                            <div class="col-md-4"><strong>Nº Contrato:</strong><br><?= htmlspecialchars($contract['contract_number'] ?? '-') ?></div>
                            <div class="col-md-4"><strong>Fornecedor:</strong><br><?= htmlspecialchars($contract['supplier_name'] ?? $contract['supplier'] ?? '-') ?></div>
                        </div>
                    <div class="row mb-3">
                            <div class="col-md-4"><strong>Unidade:</strong><br><?= htmlspecialchars($contract['unit_name']) ?></div>
                            <div class="col-md-4"><strong>Vencimento:</strong><br><?= date('d/m/Y', strtotime($contract['end_date'])) ?></div>
                            <div class="col-md-4"><strong>Valor:</strong><br>R$ <?= number_format((float)($contract['value'] ?? 0), 2, ',', '.') ?></div>
                        </div>
                    <div class="mb-3">
                        <strong>Descrição:</strong>
                        <p class="border p-2 bg-light"><?= nl2br(htmlspecialchars($contract['description'])) ?></p>
                    </div>
                    <div class="mb-3">
                        <strong>Observações:</strong>
                        <p class="border p-2 bg-light text-primary"><?= nl2br(htmlspecialchars($contract['observations'] ?? '-')) ?></p>
                    </div>

                    <?php 
                        // Buscar assinaturas
                        $stmtSigs = $pdo->prepare("SELECT * FROM contract_signatures WHERE contract_id = ? AND is_signed = 1 ORDER BY signed_at DESC");
                        $stmtSigs->execute([$contract['id']]);
                        $signatures = $stmtSigs->fetchAll();
                        if (!empty($signatures)):
                    ?>
                        <div class="mb-3">
                            <strong>Assinaturas Digitais:</strong>
                            <div class="row mt-2">
                                <?php foreach ($signatures as $sig): ?>
                                    <div class="col-md-6 mb-3">
                                        <div class="card bg-light border-0 shadow-sm">
                                            <div class="card-body p-2 text-center">
                                                <img src="<?= $sig['signature_image'] ?>" class="img-fluid mb-2" style="max-height: 80px;">
                                                <div class="small fw-bold"><?= htmlspecialchars($sig['signer_name']) ?></div>
                                                <div class="text-muted" style="font-size: 0.7rem;">
                                                     <?= date('d/m/Y H:i', strtotime($sig['signed_at'])) ?><br>
                                                     IP: <?= $sig['signer_ip'] ?>
                                                  </div>
                                                  <a href="print_signature.php?id=<?= $sig['id'] ?>" target="_blank" class="btn btn-xs btn-outline-primary mt-2" style="font-size: 0.6rem;">
                                                      <i class="fas fa-print me-1"></i> Certificado
                                                  </a>
                                              </div>
                                          </div>
                                      </div>
                                 <?php endforeach; ?>
                             </div>
                         </div>
                    <?php endif; ?>

                    <?php 
                        try {
                            $aditivos = $pdo->prepare("SELECT * FROM contract_files WHERE contract_id = ? AND is_amendment = 1 ORDER BY uploaded_at DESC");
                            $aditivos->execute([$contract['id']]);
                            $lista_aditivos = $aditivos->fetchAll();
                        } catch (PDOException $e) {
                            $lista_aditivos = [];
                        }
                        if (!empty($lista_aditivos)):
                    ?>
                        <hr>
                        <h6 class="text-warning"><i class="fas fa-file-signature me-1"></i> Aditivos Vinculados</h6>
                        <div class="table-responsive">
                            <table class="table table-sm table-bordered small">
                                <thead class="table-light">
                                    <tr>
                                        <th>Data</th>
                                        <th>Quem fez</th>
                                        <th>Observação</th>
                                        <th>Novo Vencimento</th>
                                        <th>Arquivo</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($lista_aditivos as $ad): ?>
                                    <tr>
                                        <td><?= date('d/m/Y', strtotime($ad['uploaded_at'])) ?></td>
                                        <td><?= htmlspecialchars($ad['username'] ?: 'Sistema') ?></td>
                                        <td><?= htmlspecialchars($ad['observations'] ?: '-') ?></td>
                                        <td><?= $ad['new_end_date'] ? date('d/m/Y', strtotime($ad['new_end_date'])) : '-' ?></td>
                                        <td class="text-center">
                                            <a href="serve_file.php?path=<?= urlencode($ad['file_path']) ?>" target="_blank" class="btn btn-xs btn-primary py-0 px-1" title="Ver PDF"><i class="fas fa-file-pdf"></i></a>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
                <div class="modal-footer">
                    <?php if ($contract['file_path']): ?>
                        <a href="view_with_signature.php?path=<?= urlencode($contract['file_path']) ?>&contract_id=<?= $contract['id'] ?>&uid=<?= $user_id ?>&utoken=<?= $admin_token ?>" target="_blank" class="btn btn-primary"><i class="fas fa-file-pdf me-1"></i> Ver PDF com Selo</a>
                        <a href="serve_file.php?path=<?= urlencode($contract['file_path']) ?>&uid=<?= $user_id ?>&utoken=<?= $admin_token ?>" target="_blank" class="btn btn-outline-secondary"><i class="fas fa-download me-1"></i> Baixar Original</a>
                    <?php endif; ?>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Fechar</button>
                </div>
            </div>
        </div>
    </div>
<?php endforeach; ?>

<!-- Modal Novo Contrato -->
<div class="modal fade" id="addContractModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <form method="POST" enctype="multipart/form-data">
                <input type="hidden" name="action" value="create">
                <div class="modal-header">
                    <h5 class="modal-title">Novo Contrato</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <?php if ($is_creating_from_orphan): ?>
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle me-2"></i>
                            Você está criando um novo contrato a partir do arquivo: <strong><?= basename(urldecode($orphan_file_path)) ?></strong>
                            <div class="mt-2">
                                <a href="view_orphan.php?file=<?= htmlspecialchars($orphan_file_path) ?>&source=<?= htmlspecialchars($orphan_source) ?>&full=<?= urlencode($orphan_full_path) ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                                    <i class="fas fa-eye me-1"></i> Visualizar Arquivo
                                </a>
                            </div>
                            <input type="hidden" name="orphan_file_path" value="<?= htmlspecialchars($orphan_file_path) ?>">
                            <input type="hidden" name="orphan_full_path" value="<?= htmlspecialchars($orphan_full_path) ?>">
                            <input type="hidden" name="orphan_source" value="<?= htmlspecialchars($orphan_source) ?>">
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Unidade</label>
                            <select name="unit_id" class="form-select" required>
                                <option value="">Selecione...</option>
                                <?php foreach ($units as $unit): ?>
                                    <option value="<?= $unit['id'] ?>" <?= $orphan_unit_id == $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" placeholder="Ex: Locação, Prestação de Serviço..." required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Número do Contrato</label>
                            <input type="text" name="contract_number" class="form-control" placeholder="Opcional">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Título do Contrato</label>
                            <input type="text" name="title" class="form-control" required>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Fornecedor</label>
                            <select name="supplier_id" class="form-select" required>
                                <option value="">Selecione...</option>
                                <?php foreach ($all_suppliers as $s): ?>
                                    <option value="<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">Cadastre novos em <a href="suppliers.php">Fornecedores</a>.</small>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Valor (R$)</label>
                            <input type="number" step="0.01" name="value" class="form-control">
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label>Descrição</label>
                            <textarea name="description" class="form-control" rows="2"></textarea>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-12 mb-3">
                            <label>Observações</label>
                            <textarea name="observations" class="form-control" rows="2" placeholder="Observações internas..."></textarea>
                        </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" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label>Data Fim (Vencimento)</label>
                            <input type="date" name="end_date" class="form-control" required>
                        </div>
                        <div class="col-md-4 mb-3">
                            <label>Data do Alerta</label>
                            <input type="date" name="alert_date" class="form-control">
                            <small class="text-muted">Data para destacar o contrato.</small>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label>Status</label>
                            <select name="status" class="form-select">
                                <option value="Recebido" selected>Recebido</option>
                                <option value="Em negociação">Em negociação</option>
                                <option value="Ajuste solicitado">Ajuste solicitado</option>
                                <option value="Revisão interna">Revisão interna</option>
                                <option value="Aguardando assinatura">Aguardando assinatura</option>
                                <option value="Assinado">Assinado</option>
                                <option value="Finalizado">Finalizado</option>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label>Arquivo (PDF)</label>
                            <input type="file" name="contract_file" class="form-control" accept=".pdf" <?= $is_creating_from_orphan ? 'disabled' : '' ?>>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-primary">Salvar Contrato</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Modal WhatsApp (Único e Global) -->
<div class="modal fade" id="globalWhatsappModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Enviar via WhatsApp</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Digite o número de telefone com DDD (apenas números).</p>
                <div class="input-group mb-3">
                    <span class="input-group-text"><i class="fab fa-whatsapp"></i></span>
                    <input type="tel" class="form-control" id="whatsapp-phone-global" placeholder="5541999998888">
                </div>
                <input type="hidden" id="whatsapp-message-global">
                <div class="mt-3">
                    <button class="btn btn-success w-100" onclick="confirmSendWhatsApp()"><i class="fas fa-paper-plane me-2"></i> Enviar Agora</button>
                </div>
            </div>
        </div>
    </div>
</div>

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