<?php
require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/pdfparser_autoloader.php';

use \PrinsFrank\PdfParser\PdfParser;

require_admin();

$id = $_GET['id'] ?? null;
$document = null;

if ($id) {
    $stmt = db()->prepare("SELECT * FROM kb_documents WHERE id = ?");
    $stmt->execute([$id]);
    $document = $stmt->fetch();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id = $_GET['id'] ?? null;
    $title = $_POST['title'];
    $content = $_POST['content'];
    $tags = $_POST['tags'] ?? null;
    $product_id = !empty($_POST['product_id']) ? $_POST['product_id'] : null;
    $language = $_POST['language'] ?? 'en';
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    $file_path = $document['file_path'] ?? null;
    $file_content = $document['file_content'] ?? null;

    // Handle file removal
    if ($id && isset($_POST['remove_file']) && $_POST['remove_file'] == '1') {
        if ($file_path && file_exists(__DIR__ . '/../uploads/kb_documents/' . $file_path)) {
            unlink(__DIR__ . '/../uploads/kb_documents/' . $file_path);
        }
        $file_path = null;
        $file_content = null;
    }

    // Handle new file upload
    if (isset($_FILES['pdf_file']) && $_FILES['pdf_file']['error'] === UPLOAD_ERR_OK) {
        $upload_dir = __DIR__ . '/../uploads/kb_documents/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0775, true);
        }

        $file_info = pathinfo($_FILES['pdf_file']['name']);
        $extension = strtolower($file_info['extension']);

        if ($extension === 'pdf') {
            // Delete old file if a new one is uploaded
            if ($file_path && file_exists($upload_dir . $file_path)) {
                unlink($upload_dir . $file_path);
            }

            $safe_filename = preg_replace('/[^A-Za-z0-9_.-]/', '_', $file_info['filename']);
            $new_file_name = uniqid() . '_' . $safe_filename . '.' . $extension;
            $target_path = $upload_dir . $new_file_name;

            if (move_uploaded_file($_FILES['pdf_file']['tmp_name'], $target_path)) {
                $file_path = $new_file_name;

                $parser = new PdfParser();
                $pdf = $parser->parseFile($target_path);
                $file_content = $pdf->getText();
            }
        }
    }

    if ($id) {
        $stmt = db()->prepare("UPDATE kb_documents SET title = ?, content = ?, tags = ?, product_id = ?, language = ?, is_active = ?, file_path = ?, file_content = ? WHERE id = ?");
        $stmt->execute([$title, $content, $tags, $product_id, $language, $is_active, $file_path, $file_content, $id]);
    } else {
        $stmt = db()->prepare("INSERT INTO kb_documents (title, content, tags, product_id, language, is_active, file_path, file_content) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$title, $content, $tags, $product_id, $language, $is_active, $file_path, $file_content]);
    }

    header('Location: kb_documents.php');
    exit;
}

$id = $_GET['id'] ?? null;
$document = null;

if ($id) {
    $stmt = db()->prepare("SELECT * FROM kb_documents WHERE id = ?");
    $stmt->execute([$id]);
    $document = $stmt->fetch();
}

$page_title = $id ? 'Edytuj Dokument' : 'Dodaj Dokument';
require_once __DIR__ . '/../includes/html_head.php';
?>
<body>
<?php include 'menu.php'; ?>
<main class="container my-5">
            <h1><?= $page_title ?></h1>

            <div class="card">
                <div class="card-body">
                    <form action="edit_kb_document.php<?= $id ? '?id=' . $id : '' ?>" method="POST" enctype="multipart/form-data">
                        <div class="mb-3">
                            <label for="title" class="form-label">Tytuł</label>
                            <input type="text" class="form-control" id="title" name="title" value="<?= htmlspecialchars($document['title'] ?? '') ?>" required>
                        </div>
                        <div class="mb-3">
                            <label for="content" class="form-label">Treść</label>
                            <textarea class="form-control" id="content" name="content" rows="10" required><?= htmlspecialchars($document['content'] ?? '') ?></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="tags" class="form-label">Tagi (oddzielone przecinkami)</label>
                                    <input type="text" class="form-control" id="tags" name="tags" value="<?= htmlspecialchars($document['tags'] ?? '') ?>">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="product_id" class="form-label">Produkt</label>
                                    <select class="form-control" id="product_id" name="product_id">
                                        <option value="">Brak</option>
                                        <?php
                                        $stmt = db()->query("SELECT id, name FROM products ORDER BY name");
                                        while ($product = $stmt->fetch()) {
                                            $selected = ($document['product_id'] ?? '') == $product['id'] ? 'selected' : '';
                                            echo "<option value=\"{$product['id']}\" {$selected}>" . htmlspecialchars($product['name']) . "</option>";
                                        }
                                        ?>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="language" class="form-label">Język</label>
                                    <select class="form-control" id="language" name="language">
                                        <option value="en" <?= ($document['language'] ?? 'en') == 'en' ? 'selected' : '' ?>>Angielski</option>
                                        <option value="pl" <?= ($document['language'] ?? '') == 'pl' ? 'selected' : '' ?>>Polski</option>
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="pdf_file" class="form-label">Plik PDF</label>
                                    <input type="file" class="form-control" id="pdf_file" name="pdf_file" accept=".pdf">
                                    <?php if (!empty($document['file_path'])): ?>
                                        <div class="mt-2">
                                            Obecny plik: <a href="/uploads/kb_documents/<?= htmlspecialchars($document['file_path']) ?>" target="_blank"><?= htmlspecialchars($document['file_path']) ?></a>
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="remove_file" id="remove_file" value="1">
                                                <label class="form-check-label" for="remove_file">Usuń obecny plik</label>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3 form-check form-switch">
                                    <input class="form-check-input" type="checkbox" id="is_active" name="is_active" value="1" <?= ($document['is_active'] ?? true) ? 'checked' : '' ?> >
                                    <label class="form-check-label" for="is_active">Aktywny</label>
                                </div>
                            </div>
                        </div>

                        <button type="submit" class="btn btn-primary"><i class="fa-solid fa-save"></i> Zapisz</button>
                        <a href="kb_documents.php" class="btn btn-secondary">Anuluj</a>
                    </form>
                </div>
            </div>


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