<?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();
$id = $_GET['id'] ?? null;
if (!$id) {
    header('Location: units.php');
    exit;
}

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

if (!$unit) {
    die("Unidade não encontrada.");
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $oldName = $unit['name'];
    $name = $_POST['name'];
    $document = $_POST['document'];
    $email = $_POST['email'];
    $phone = $_POST['phone'];
    $address = $_POST['address'];

    $stmt = $pdo->prepare("UPDATE units SET name = ?, document = ?, email = ?, phone = ?, address = ? WHERE id = ?");
    if ($stmt->execute([$name, $document, $email, $phone, $address, $id])) {
        if ($oldName !== $name) {
            $oldFolderName = cfh_sanitize_unit_folder($oldName);
            $newFolderName = cfh_sanitize_unit_folder($name);

            if ($oldFolderName !== $newFolderName) {
                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);
                        }
                        $moved = $nc->moveFile($remoteRoot . '/' . $oldFolderName, $remoteRoot . '/' . $newFolderName);
                    if (!$moved) {
                            $nc->createFolder($remoteRoot . '/' . $newFolderName);
                    }
                } catch (Throwable $e) {
                    $message = "Unidade atualizada, mas não foi possível atualizar a pasta no Nextcloud: " . $e->getMessage();
                }

                $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);

                if ($nc_local_contracts_root !== '' && is_dir($nc_local_contracts_root)) {
                    $oldFolder = $nc_local_contracts_root . DIRECTORY_SEPARATOR . $oldFolderName;
                    $newFolder = $nc_local_contracts_root . DIRECTORY_SEPARATOR . $newFolderName;

                    if (is_dir($oldFolder) && !is_dir($newFolder)) {
                        @rename($oldFolder, $newFolder);
                    }
                    if (!is_dir($newFolder)) {
                        @mkdir($newFolder, 0777, true);
                    }
                }
            }
        }
        
        if ($message === '') {
            $message = "Unidade atualizada com sucesso!";
        }
        // Refresh data
        $stmt = $pdo->prepare("SELECT * FROM units WHERE id = ?");
        $stmt->execute([$id]);
        $unit = $stmt->fetch();
    } else {
        $message = "Erro ao atualizar unidade.";
    }
}

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

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

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

    <div class="card">
        <div class="card-body">
            <form method="POST">
                <div class="mb-3">
                    <label>Nome da Unidade</label>
                    <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($unit['name']) ?>" required>
                </div>
                <div class="mb-3">
                    <label>Documento (CPF/CNPJ)</label>
                    <input type="text" name="document" class="form-control" value="<?= htmlspecialchars($unit['document']) ?>">
                </div>
                <div class="mb-3">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($unit['email']) ?>">
                </div>
                <div class="mb-3">
                    <label>Telefone</label>
                    <input type="text" name="phone" class="form-control" value="<?= htmlspecialchars($unit['phone']) ?>">
                </div>
                <div class="mb-3">
                    <label>Endereço</label>
                    <textarea name="address" class="form-control"><?= htmlspecialchars($unit['address']) ?></textarea>
                </div>
                <button type="submit" class="btn btn-primary">Salvar Alterações</button>
            </form>
        </div>
    </div>
</div>

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