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

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

$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_local_contracts_root = cfh_extract_contracts_root((string)$nc_path);

$stmtDays = $pdo->prepare("SELECT setting_value FROM system_settings WHERE setting_key = 'alert_days'");
$stmtDays->execute();
$alert_days_setting = (int)($stmtDays->fetchColumn() ?: 30);
$alert_days_setting = $alert_days_setting > 0 ? $alert_days_setting : 30;
$expiring_limit_date = date('Y-m-d', strtotime('+' . $alert_days_setting . ' days'));

function unit_count_local_files($dir) {
    $dir = (string)$dir;
    if ($dir === '' || !is_dir($dir)) {
        return 0;
    }

    $count = 0;
    try {
        foreach (new DirectoryIterator($dir) as $fileInfo) {
            if ($fileInfo->isDot() || !$fileInfo->isFile()) {
                continue;
            }
            $name = $fileInfo->getFilename();
            if ($name === '' || strpos($name, '.') === 0) {
                continue;
            }
            $count++;
        }
    } catch (Throwable $e) {
        return 0;
    }

    return $count;
}

// Handle Create Unit
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'create') {
    $name = $_POST['name'];
    $document = $_POST['document'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];

    $stmt = $pdo->prepare("INSERT INTO units (name, document, email, phone, address) VALUES (?, ?, ?, ?, ?)");
    if ($stmt->execute([$name, $document, $email, $phone, $address])) {
        $message = "Unidade adicionada com sucesso!";
        
        // Criar pasta no Nextcloud (WebDAV)
        try {
            $nc = new Nextcloud();
            $unitFolder = preg_replace('/[\/:*?"<>|]/', '_', $name);
            // Criar pasta principal /CONTRATOS se não existir e depois a da unidade
            $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);
        } catch (Exception $e) {
            $message .= " (Erro ao criar pasta no Nextcloud: " . $e->getMessage() . ")";
        }
        
        // Criar pasta local para sincronização (opcional se usar WebDAV direto)
        if ($nc_local_contracts_root !== '' && is_dir($nc_local_contracts_root)) {
            $unitFolder = cfh_sanitize_unit_folder($name);
            $localUnitPath = $nc_local_contracts_root . DIRECTORY_SEPARATOR . $unitFolder;
            if (!is_dir($localUnitPath)) {
                @mkdir($localUnitPath, 0777, true);
            }
        }
    } else {
        $message = "Erro ao adicionar unidade.";
    }
}

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

$units = [];
try {
    if (!isset($_SESSION['units_sync_ts'])) {
        $_SESSION['units_sync_ts'] = 0;
    }
    $lastSync = (int)$_SESSION['units_sync_ts'];
    if ($lastSync <= 0 || (time() - $lastSync) > 300) {
        $nc = new Nextcloud();
        $configuredRoot = trim(str_replace('\\', '/', (string)cfh_get_remote_contracts_root()), '/');
        $probeCandidates = [];
        if ($configuredRoot !== '') {
            $probeCandidates[] = $configuredRoot;
        }
        $probeCandidates[] = 'CONTRATOS';
        $probeCandidates[] = 'CSC/CONTRATOS';
        $probeCandidates[] = 'CONTRATOS (2)';

        foreach ($nc->listRootDirectories() as $dir) {
            $candidatePath = trim((string)($dir['relative_path'] ?? ''), '/');
            $candidateName = (string)($dir['name'] ?? '');
            $haystack = $candidateName !== '' ? $candidateName : $candidatePath;
            if ($candidatePath !== '' && stripos($haystack, 'CONTRATOS') !== false) {
                $probeCandidates[] = $candidatePath;
            }
        }
        $probeCandidates = array_values(array_unique(array_filter(array_map(function($c) {
            return trim((string)$c, '/');
        }, $probeCandidates), 'strlen')));

        $bestEntries = [];
        $bestCount = -1;
        $bestCandidate = '';
        foreach ($probeCandidates as $candidate) {
            $info = $nc->listImmediateEntries($candidate);
            $entries = isset($info['entries']) && is_array($info['entries']) ? $info['entries'] : [];
            $dirEntries = array_values(array_filter($entries, function($e) {
                return is_array($e) && !empty($e['is_dir']) && trim((string)($e['name'] ?? '')) !== '';
            }));
            $dirCount = count($dirEntries);
            if ($dirCount > $bestCount) {
                $bestCount = $dirCount;
                $bestEntries = $dirEntries;
                $bestCandidate = $candidate;
            }
        }

        if ($bestCount > 0 && !empty($bestEntries)) {
            $stmtInsert = $pdo->prepare("INSERT IGNORE INTO units (name) VALUES (?)");
            foreach ($bestEntries as $entry) {
                $name = trim((string)($entry['name'] ?? ''));
                if ($name === '') {
                    continue;
                }
                $stmtInsert->execute([$name]);
            }
        }

        $_SESSION['units_sync_ts'] = time();
        $_SESSION['units_sync_root'] = $bestCandidate;
    }
} catch (Throwable $e) {
}

// --- Lógica de Sincronização com Pastas do Nextcloud ---
if ($nc_local_contracts_root !== '' && is_dir($nc_local_contracts_root)) {
    $directories = glob($nc_local_contracts_root . DIRECTORY_SEPARATOR . '*', GLOB_ONLYDIR);
    if ($directories) {
        foreach ($directories as $dirPath) {
            $folderName = basename($dirPath);
            
            // Verificar se esta pasta já existe no banco (pelo nome)
            $stmtCheck = $pdo->prepare("SELECT id FROM units WHERE name = ?");
            $stmtCheck->execute([$folderName]);
            if (!$stmtCheck->fetch()) {
                // Não existe no banco, vamos adicionar
                $stmtInsert = $pdo->prepare("INSERT INTO units (name) VALUES (?)");
                $stmtInsert->execute([$folderName]);
            }
        }
    }
}
// --------------------------------------------------------

$sql = "
    SELECT u.*, 
    (SELECT COUNT(*) FROM contracts WHERE unit_id = u.id) as total_contracts,
    (SELECT COUNT(*) FROM contracts WHERE unit_id = u.id AND status = 'active') as active_contracts,
    (SELECT COUNT(*) FROM contracts WHERE unit_id = u.id AND status = 'active' AND end_date BETWEEN CURDATE() AND ?) as expiring_contracts,
    (SELECT MIN(end_date) FROM contracts WHERE unit_id = u.id AND status = 'active' AND end_date BETWEEN CURDATE() AND ?) as next_expiring_date,
    (SELECT COUNT(*) FROM contracts WHERE unit_id = u.id AND end_date < CURDATE() AND status NOT IN ('completed', 'canceled')) as expired_contracts,
    (SELECT MIN(end_date) FROM contracts WHERE unit_id = u.id AND end_date < CURDATE() AND status NOT IN ('completed', 'canceled')) as oldest_expired_date,
    (SELECT COUNT(*) FROM contract_files cf JOIN contracts c ON cf.contract_id = c.id WHERE c.unit_id = u.id AND (cf.is_amendment = 1 OR cf.file_path LIKE 'Aditivo_%' OR cf.file_path LIKE '%/Aditivo_%')) as amendment_count
    FROM units u 
    ORDER BY u.created_at DESC
";

try {
    $stmtUnits = $pdo->prepare($sql);
    $stmtUnits->execute([$expiring_limit_date, $expiring_limit_date]);
    $units = $stmtUnits->fetchAll();
} catch (PDOException $e) {
    // Fallback se as novas colunas/tabelas ainda não existirem plenamente
    try {
        $stmtUnits = $pdo->prepare("
            SELECT u.*, 
            (SELECT COUNT(*) FROM contracts WHERE unit_id = u.id) as total_contracts,
            (SELECT COUNT(*) FROM contracts WHERE unit_id = u.id AND status = 'active') as active_contracts,
            (SELECT COUNT(*) FROM contracts WHERE unit_id = u.id AND status = 'active' AND end_date BETWEEN CURDATE() AND ?) as expiring_contracts,
            (SELECT MIN(end_date) FROM contracts WHERE unit_id = u.id AND status = 'active' AND end_date BETWEEN CURDATE() AND ?) as next_expiring_date,
            (SELECT COUNT(*) FROM contracts WHERE unit_id = u.id AND end_date < CURDATE() AND status NOT IN ('completed', 'canceled')) as expired_contracts,
            (SELECT MIN(end_date) FROM contracts WHERE unit_id = u.id AND end_date < CURDATE() AND status NOT IN ('completed', 'canceled')) as oldest_expired_date,
            (SELECT COUNT(*) FROM contract_files cf JOIN contracts c ON cf.contract_id = c.id WHERE c.unit_id = u.id AND (cf.file_path LIKE 'Aditivo_%' OR cf.file_path LIKE '%/Aditivo_%')) as amendment_count
            FROM units u 
            ORDER BY u.created_at DESC
        ");
        $stmtUnits->execute([$expiring_limit_date, $expiring_limit_date]);
        $units = $stmtUnits->fetchAll();
    } catch (Throwable $e2) {
        $units = [];
    }
}

if (is_array($units)) {
    foreach ($units as &$unit) {
        $unitFolder = cfh_sanitize_unit_folder($unit['name'] ?? '');
        $unitDir = ($nc_local_contracts_root !== '' ? $nc_local_contracts_root : (string)$nc_path) . DIRECTORY_SEPARATOR . $unitFolder;
        $unit['folder_files'] = unit_count_local_files($unitDir);
        $unit['folder_path'] = $unitDir;
    }
    unset($unit);
}

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

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2>Gerenciar Unidades</h2>
        <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUnitModal">
            <i class="fas fa-plus"></i> Nova Unidade
        </button>
    </div>

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

    <div class="card">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>Nome</th>
                            <th>Arquivos na Pasta</th>
                            <th>Total Contratos</th>
                            <th>Ativos</th>
                            <th>A Vencer (<?= (int)$alert_days_setting ?>d)</th>
                            <th>Vencido</th>
                            <th>Aditivos</th>
                            <th>Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($units)): ?>
                        <tr>
                            <td colspan="8" class="text-center text-muted py-4">Nenhuma unidade encontrada.</td>
                        </tr>
                        <?php endif; ?>
                        <?php foreach ($units as $unit): ?>
                        <?php 
                            $row_class = '';
                            if ($unit['expired_contracts'] > 0) {
                                $row_class = 'table-danger';
                            } elseif ($unit['expiring_contracts'] > 0) {
                                $row_class = 'table-warning';
                            }
                        ?>
                        <tr class="<?= $row_class ?>">
                            <td><?= htmlspecialchars($unit['name']) ?></td>
                            <td class="text-center">
                                <span class="badge bg-dark"><?= (int)($unit['folder_files'] ?? 0) ?></span>
                            </td>
                            <td class="text-center"><span class="badge bg-secondary"><?= $unit['total_contracts'] ?></span></td>
                            <td class="text-center"><span class="badge bg-success"><?= $unit['active_contracts'] ?></span></td>
                            <td class="text-center">
                                <span class="badge bg-<?= $unit['expiring_contracts'] > 0 ? 'warning text-dark' : 'light text-dark' ?>">
                                    <?= $unit['expiring_contracts'] ?>
                                </span>
                                <?php if ($unit['expiring_contracts'] > 0): ?>
                                    <div class="small text-warning fw-bold mt-1" style="filter: brightness(0.7);">
                                        <?= date('d/m/Y', strtotime($unit['next_expiring_date'])) ?>
                                    </div>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                <?php if ($unit['expired_contracts'] > 0): ?>
                                    <span class="badge bg-danger"><?= $unit['expired_contracts'] ?></span>
                                    <div class="small text-danger fw-bold mt-1">
                                        <?= date('d/m/Y', strtotime($unit['oldest_expired_date'])) ?>
                                    </div>
                                <?php else: ?>
                                    <span class="text-muted small">0</span>
                                <?php endif; ?>
                            </td>
                            <td class="text-center">
                                 <span class="badge bg-info text-dark">
                                     <i class="fas fa-file-signature me-1"></i> <?= $unit['amendment_count'] ?>
                                 </span>
                             </td>
                             <td>
                                <a href="edit_unit.php?id=<?= $unit['id'] ?>" class="btn btn-sm btn-warning"><i class="fas fa-edit"></i></a>
                                <a href="units.php?delete=<?= $unit['id'] ?>" class="btn btn-sm btn-danger" onclick="return confirm('Tem certeza?')"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Modal Adicionar Unidade -->
<div class="modal fade" id="addUnitModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="POST">
                <input type="hidden" name="action" value="create">
                <div class="modal-header">
                    <h5 class="modal-title">Nova Unidade</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label>Nome da Unidade</label>
                        <input type="text" name="name" class="form-control" required>
                    </div>
                    <div class="mb-3">
                        <label>Documento (CPF/CNPJ)</label>
                        <input type="text" name="document" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label>Email</label>
                        <input type="email" name="email" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label>Telefone</label>
                        <input type="text" name="phone" class="form-control">
                    </div>
                    <div class="mb-3">
                        <label>Endereço</label>
                        <textarea name="address" class="form-control"></textarea>
                    </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</button>
                </div>
            </form>
        </div>
    </div>
</div>

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