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

$pdo = get_db_connection();
$message = '';
$error_message = '';

// Buscar caminho configurado no banco ou usar o padrão
$stmtPath = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'nc_path'");
$stmtPath->execute();
$nc_path = $stmtPath->fetchColumn() ?: NC_CONTRACTS_PATH_DEFAULT;
$nc_remote_display = '/' . get_nextcloud_remote_root($nc_path);

// Lógica de vinculação
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'link_file') {
    $contract_id = $_POST['contract_id'] ?: null;
    $unit_id = $_POST['unit_id'] ?: null;
    $file_path = urldecode((string)($_POST['file_path'] ?? ''));
    $full_path = urldecode((string)($_POST['full_path'] ?? ''));
    $source = $_POST['source'] ?? 'local';
    $is_amendment = isset($_POST['is_amendment']);
    $amendment_obs = $_POST['amendment_obs'] ?? null;
    $new_end_date = $_POST['new_end_date'] ?? null;

    if (!$contract_id && !$unit_id) {
        $error_message = "Você deve selecionar um Contrato para vincular ou uma Unidade para organizar o arquivo.";
    } else {
        // Se vinculou a um contrato, pegar a unidade dele se não foi informada manualmente
        if ($contract_id && !$unit_id) {
            $stmtU = $pdo->prepare("SELECT unit_id FROM contracts WHERE id = ?");
            $stmtU->execute([$contract_id]);
            $unit_id = $stmtU->fetchColumn();
        }

        try {
            $nc = new Nextcloud();
            $fileName = basename($file_path);
            
            // Renomear se for aditivo
            if ($is_amendment && strpos($fileName, 'Aditivo_') !== 0) {
                $fileName = 'Aditivo_' . $fileName;
            }

            $final_file_path = $file_path;
            $final_full_path = $full_path;
            $backup_file_path = '';

            // 1. Se informou Unidade, mover arquivo para a pasta correta no Nextcloud
            if ($unit_id) {
                $stmtUnitName = $pdo->prepare("SELECT name FROM units WHERE id = ?");
                $stmtUnitName->execute([$unit_id]);
                $unitName = $stmtUnitName->fetchColumn();
                
                if ($unitName) {
                    $organized = cfh_organize_contract_file($nc, $source, $file_path, $full_path, $unitName, $fileName);
                    $final_file_path = $organized['remote_path'];
                    $final_full_path = $organized['full_path'];
                    $backup_file_path = $organized['backup_path'];
                }
            }

            // O caminho a ser gravado no banco de dados agora é SEMPRE o caminho do Nextcloud
            $file_path_db = $final_file_path;
            if ($backup_file_path === '' && $source === 'remote') {
                $backup_file_path = cfh_backup_from_remote($nc, $file_path_db, basename($file_path_db));
            } elseif ($backup_file_path === '' && $final_full_path && file_exists($final_full_path)) {
                $backup_file_path = cfh_backup_from_local($final_full_path, $file_path_db, basename($file_path_db));
            }

            // 3. Vincular ao contrato se selecionado
            if ($contract_id) {
                if (!$is_amendment) {
                    $stmt = $pdo->prepare("UPDATE contracts SET file_path = ? WHERE id = ?");
                    $stmt->execute([$file_path_db, $contract_id]);
                } else if ($new_end_date) {
                    $stmt = $pdo->prepare("UPDATE contracts SET end_date = ? WHERE id = ?");
                    $stmt->execute([$new_end_date, $contract_id]);
                }
                
                try {
                    $stmtHistory = $pdo->prepare("INSERT INTO contract_files (contract_id, file_path, is_amendment, observations, username, user_id, new_end_date) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $stmtHistory->execute([
                        $contract_id, 
                        $file_path_db, 
                        $is_amendment ? 1 : 0, 
                        $amendment_obs, 
                        $_SESSION['username'] ?? 'System', 
                        $_SESSION['user_id'] ?? null, 
                        $new_end_date ?: null
                    ]);
                } catch (PDOException $e) {
                    // Fallback se as novas colunas ainda não existirem no banco de produção
                    $stmtHistory = $pdo->prepare("INSERT INTO contract_files (contract_id, file_path) VALUES (?, ?)");
                    $stmtHistory->execute([$contract_id, $file_path_db]);
                }
                
                $action_log = $is_amendment ? 'amendment_linked' : 'linked_from_nextcloud';
                log_contract_history($contract_id, $action_log, [
                    'file' => $file_path_db,
                    'full_path' => $final_full_path,
                    'backup_file' => $backup_file_path,
                    'observations' => $amendment_obs,
                    'new_end_date' => $new_end_date
                ]);
                header("Location: sync_manager.php?msg=linked&amendment=" . ($is_amendment ? 1 : 0));
                exit;
            } else if ($unit_id) {
                header("Location: sync_manager.php?msg=organized");
                exit;
            }

        } catch (Exception $e) {
            $error_message = "Erro no processamento: " . $e->getMessage();
        }
    }
}

// Lógica de exclusão
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete_file') {
    $file_path = urldecode((string)($_POST['file_path'] ?? ''));
    $source = $_POST['source'] ?? 'local';
    $full_path = urldecode((string)($_POST['full_path'] ?? ''));

    $deleted = false;
    // 1. Deletar do Nextcloud Remoto
    if ($source === 'remote') {
        try {
            $nc = new Nextcloud();
            if ($nc->deleteFile($file_path)) {
                $deleted = true;
            }
        } catch (Exception $e) {
            $message = "Erro ao deletar arquivo no Nextcloud: " . $e->getMessage();
        }
    }

    // 2. Deletar do sistema de arquivos local
    if (file_exists($full_path)) {
        if (unlink($full_path)) {
            $deleted = true;
        }
    }

    if ($deleted) {
        cfh_remove_backup($file_path, basename($file_path));
        header("Location: sync_manager.php?msg=deleted&file=" . urlencode(basename($file_path)));
        exit;
    } else if (empty($message)) {
        $message = "Erro: Não foi possível excluir o arquivo ou ele já foi removido.";
    }
}

// Handle messages from redirect
if (isset($_GET['msg'])) {
    if ($_GET['msg'] === 'linked') {
        $is_amendment = ($_GET['amendment'] ?? 0) == 1;
        $message = "Arquivo vinculado com sucesso" . ($is_amendment ? " como Aditivo!" : "!");
    }
    if ($_GET['msg'] === 'organized') $message = "Arquivo organizado na pasta da unidade com sucesso!";
    if ($_GET['msg'] === 'deleted') $message = "Arquivo '" . htmlspecialchars($_GET['file'] ?? '') . "' excluído com sucesso!";
}

$force_refresh = isset($_GET['refresh']) && $_GET['refresh'] == 1;
$orphaned_files = [];
$debug = null;
try {
    $orphaned_files = get_orphaned_nextcloud_files($force_refresh, $debug);
} catch (Exception $e) {
    $error_message = "Erro ao atualizar lista do servidor: " . $e->getMessage();
}
$contracts = $pdo->query("SELECT id, title, supplier, unit_id FROM contracts ORDER BY title ASC")->fetchAll();
$units_list = $pdo->query("SELECT id, name FROM units ORDER BY name ASC")->fetchAll();

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

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Gerenciar Arquivos Pendentes</h2>
        <div>
            <a href="sync_manager.php?refresh=1" class="btn btn-outline-primary me-2"><i class="fas fa-sync"></i> Recarregar do Servidor</a>
            <a href="dashboard.php" class="btn btn-secondary">Voltar ao Dashboard</a>
        </div>
    </div>

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

    <?php if ($error_message): ?>
        <div class="alert alert-danger">
            <i class="fas fa-exclamation-circle me-2"></i>
            <?= htmlspecialchars($error_message) ?>
        </div>
    <?php endif; ?>

    <?php if (isset($_GET['debug']) && $_GET['debug'] == 1): ?>
        <?php
            $debugToShow = $debug;
            try {
                if (is_array($debugToShow) && isset($debugToShow['remote_root'])) {
                    $remoteRoot = trim((string)$debugToShow['remote_root'], '/');
                    $probeName = trim((string)($_GET['probe'] ?? 'Colégio Imaculada Virgem Maria - Prudentopolis'));
                    $probePath = $probeName !== '' ? ($remoteRoot !== '' ? ($remoteRoot . '/' . $probeName) : $probeName) : '';

                    $ncDebug = new Nextcloud();
                    $debugToShow['debug_webdav_user'] = $ncDebug->getActiveWebdavUser();
                    $debugToShow['root_directories'] = $ncDebug->listRootDirectories();
                    $debugToShow['probe_csc'] = $ncDebug->listImmediateEntries('CSC');
                    $debugToShow['probe_csc_contratos'] = $ncDebug->listImmediateEntries('CSC/CONTRATOS');
                    $debugToShow['probe_root'] = $ncDebug->listImmediateEntries($remoteRoot);
                    if ($probePath !== '') {
                        $debugToShow['probe_path'] = $probePath;
                        $debugToShow['probe_entries'] = $ncDebug->listImmediateEntries($probePath);
                    }
                }
            } catch (Throwable $e) {
                if (is_array($debugToShow)) {
                    $debugToShow['debug_error'] = $e->getMessage();
                }
            }
        ?>
        <div class="card shadow-sm mb-4">
            <div class="card-header bg-dark text-white">
                Debug Nextcloud
            </div>
            <div class="card-body">
                <pre style="white-space: pre-wrap; margin: 0;"><?= htmlspecialchars(json_encode($debugToShow, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)) ?></pre>
            </div>
        </div>
    <?php endif; ?>

    <div class="card shadow-sm">
        <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
            <span>Arquivos detectados na pasta do Nextcloud (Não vinculados)</span>
            <small class="text-white-50">Pasta remota: <?= $nc_remote_display ?></small>
        </div>
        <div class="card-body">
            <?php if (empty($orphaned_files)): ?>
                <div class="text-center py-5">
                    <i class="fas fa-check-circle fa-4x text-success mb-3"></i>
                    <h4>Tudo em ordem!</h4>
                    <p class="text-muted">Não encontramos arquivos pendentes de vinculação no Nextcloud.</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover align-middle">
                        <thead class="table-light">
                            <tr>
                                <th>Arquivo</th>
                                <th>Pasta/Unidade</th>
                                <th>Data Modificação</th>
                                <th>Tamanho</th>
                                <th>Ação</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($orphaned_files as $file): ?>
                            <tr>
                                <td>
                                    <i class="fas fa-file-pdf text-danger me-2"></i>
                                    <?= htmlspecialchars($file['name']) ?>
                                    <?php if ($file['source'] === 'remote'): ?>
                                        <span class="badge bg-info ms-1" title="Arquivo detectado diretamente no servidor Nextcloud"><i class="fas fa-cloud me-1"></i> Remoto</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <span class="badge bg-light text-dark border">
                                        <i class="fas fa-folder me-1"></i> <?= htmlspecialchars($file['unit_folder']) ?>
                                    </span>
                                </td>
                                <td><?= date('d/m/Y H:i', $file['mtime']) ?></td>
                                <td><?= round($file['size'] / 1024 / 1024, 2) ?> MB</td>
                                <td>
                                    <a href="view_orphan.php?file=<?= urlencode($file['path']) ?>&source=<?= $file['source'] ?>&full=<?= urlencode($file['full_path']) ?>" target="_blank" class="btn btn-sm btn-info" title="Visualizar arquivo">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <button class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#linkModal<?= md5($file['path']) ?>">
                                        <i class="fas fa-link me-1"></i> Vincular
                                    </button>
                                    <form method="POST" class="d-inline" onsubmit="return confirm('Tem certeza que deseja excluir este arquivo permanentemente?')">
                                        <input type="hidden" name="action" value="delete_file">
                                        <input type="hidden" name="file_path" value="<?= htmlspecialchars($file['path']) ?>">
                                        <input type="hidden" name="source" value="<?= $file['source'] ?>">
                                        <input type="hidden" name="full_path" value="<?= htmlspecialchars($file['full_path']) ?>">
                                        <button type="submit" class="btn btn-sm btn-danger" title="Excluir arquivo permanentemente">
                                            <i class="fas fa-trash"></i>
                                        </button>
                                    </form>
                                </td>
                            </tr>

                            <!-- Modal Vincular -->
                            <div class="modal fade" id="linkModal<?= md5($file['path']) ?>" tabindex="-1">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <form method="POST">
                                            <input type="hidden" name="action" value="link_file">
                                            <input type="hidden" name="file_path" value="<?= htmlspecialchars($file['path']) ?>">
                                            <input type="hidden" name="full_path" value="<?= htmlspecialchars($file['full_path']) ?>">
                                            <input type="hidden" name="source" value="<?= $file['source'] ?>">
                                            <div class="modal-header">
                                                <h5 class="modal-title">Vincular Arquivo</h5>
                                                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                            </div>
                                            <div class="modal-body">
                                                <p class="small text-muted mb-3">Arquivo: <code><?= htmlspecialchars($file['name']) ?></code></p>
                                                <div class="mb-3 text-center">
                                                    <a href="view_orphan.php?file=<?= urlencode($file['path']) ?>&source=<?= $file['source'] ?>&full=<?= urlencode($file['full_path']) ?>" target="_blank" class="btn btn-sm btn-outline-info">
                                                        <i class="fas fa-eye me-1"></i> Visualizar Arquivo antes de vincular
                                                    </a>
                                                </div>
                                                <?php if ($file['source'] === 'remote'): ?>
                                                    <div class="alert alert-warning p-2 small mb-3">
                                                        <i class="fas fa-info-circle me-1"></i> Este arquivo foi detectado no Nextcloud. O sistema irá vinculá-lo e organizar na pasta correta.
                                                    </div>
                                                <?php endif; ?>
                                                
                                                <div class="mb-3">
                                                    <label class="form-label">1. Selecione a Unidade:</label>
                                                    <select name="unit_id" class="form-select unit-selector">
                                                        <option value="">-- Selecione uma unidade --</option>
                                                        <?php foreach ($units_list as $u): ?>
                                                            <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['name']) ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <small class="text-muted">O arquivo será movido para a pasta desta unidade no Nextcloud.</small>
                                                </div>

                                                <div class="mb-3">
                                                    <label class="form-label">2. Vincular a Contrato Existente (Opcional):</label>
                                                    <select name="contract_id" class="form-select contract-selector">
                                                        <option value="">-- Selecione um contrato --</option>
                                                        <?php foreach ($contracts as $c): ?>
                                                            <option value="<?= $c['id'] ?>" data-unit="<?= $c['unit_id'] ?>" style="display:none;"><?= htmlspecialchars($c['title']) ?> (<?= htmlspecialchars($c['supplier']) ?>)</option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <small class="text-info d-block mt-1 info-unit-select">Selecione primeiro a unidade para listar os contratos.</small>
                                                </div>

                                                <div class="form-check mb-3">
                                                    <input class="form-check-input amendment-check" type="checkbox" name="is_amendment" value="1" id="amendment<?= md5($file['path']) ?>" onchange="toggleAmendmentFields(this)">
                                                    <label class="form-check-label" for="amendment<?= md5($file['path']) ?>">
                                                        Este arquivo é um <b>Aditivo</b> ao contrato
                                                    </label>
                                                </div>

                                                <div class="amendment-fields" style="display: none;">
                                                    <div class="mb-3">
                                                        <label class="form-label small">Observação do Aditivo:</label>
                                                        <textarea name="amendment_obs" class="form-control form-control-sm" rows="2" placeholder="Descreva o que este aditivo altera..."></textarea>
                                                    </div>
                                                    <div class="mb-3">
                                                        <label class="form-label small">Nova Data de Vencimento (se houver):</label>
                                                        <input type="date" name="new_end_date" class="form-control form-control-sm">
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="modal-footer">
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                                                <a href="#" onclick="createContractFromOrphan('<?= urlencode($file['path']) ?>', '<?= $file['source'] ?>', this, '<?= urlencode($file['full_path']) ?>')" class="btn btn-success"><i class="fas fa-plus me-1"></i> Criar Novo Contrato</a>
                                                <button type="submit" class="btn btn-primary">Confirmar Vínculo</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Filtrar contratos por unidade selecionada
    document.querySelectorAll('.unit-selector').forEach(unitSelect => {
        unitSelect.addEventListener('change', function() {
            const unitId = this.value;
            const modalBody = this.closest('.modal-body');
            const contractSelect = modalBody.querySelector('.contract-selector');
            const infoText = modalBody.querySelector('.info-unit-select');
            
            // Resetar contrato
            contractSelect.value = "";
            
            if (!unitId) {
                // Esconder todos os contratos
                contractSelect.querySelectorAll('option').forEach(opt => {
                    if (opt.value !== "") opt.style.display = 'none';
                });
                infoText.textContent = "Selecione primeiro a unidade para listar os contratos.";
                infoText.className = "text-info d-block mt-1 info-unit-select";
            } else {
                let count = 0;
                contractSelect.querySelectorAll('option').forEach(opt => {
                    if (opt.value === "") {
                        opt.style.display = 'block';
                    } else if (opt.getAttribute('data-unit') == unitId) {
                        opt.style.display = 'block';
                        count++;
                    } else {
                        opt.style.display = 'none';
                    }
                });
                
                if (count > 0) {
                    infoText.textContent = `Encontrados ${count} contrato(s) para esta unidade.`;
                    infoText.className = "text-success d-block mt-1 info-unit-select";
                } else {
                    infoText.textContent = "Nenhum contrato encontrado para esta unidade.";
                    infoText.className = "text-warning d-block mt-1 info-unit-select";
                }
            }
        });
    });
});

function toggleAmendmentFields(checkbox) {
    const modalBody = checkbox.closest('.modal-body');
    const fields = modalBody.querySelector('.amendment-fields');
    const contractSelect = modalBody.querySelector('.contract-selector');
    const createBtn = modalBody.closest('.modal-content').querySelector('.btn-success');
    const linkBtn = modalBody.closest('.modal-content').querySelector('button[type="submit"]');

    if (checkbox.checked) {
        if (fields) fields.style.display = 'block';
        if (contractSelect) contractSelect.setAttribute('required', 'required');
        if (createBtn) createBtn.style.display = 'none'; // Não pode criar NOVO contrato se for aditivo
        if (linkBtn) linkBtn.textContent = 'Vincular como Aditivo';
    } else {
        if (fields) fields.style.display = 'none';
        if (contractSelect) contractSelect.removeAttribute('required');
        if (createBtn) createBtn.style.display = 'inline-block';
        if (linkBtn) linkBtn.innerHTML = '<i class="fas fa-link me-1"></i> Vincular';
    }
}

function createContractFromOrphan(filePath, source, btn, fullPath) {
    const modal = btn.closest('.modal-content');
    const unitId = modal.querySelector('select[name="unit_id"]').value;
    const isAmendment = modal.querySelector('input[name="is_amendment"]').checked ? 1 : 0;
    const obs = modal.querySelector('textarea[name="amendment_obs"]').value;
    const date = modal.querySelector('input[name="new_end_date"]').value;
    
    let url = `contracts.php?action=create_from_orphan&file_path=${filePath}&source=${source}&full_path=${fullPath}`;
    if (unitId) url += `&unit_id=${unitId}`;
    if (isAmendment) {
        url += `&is_amendment=1`;
        if (obs) url += `&amendment_obs=${encodeURIComponent(obs)}`;
        if (date) url += `&new_end_date=${date}`;
    }
    
    window.location.href = url;
}
</script>

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