<?php
declare(strict_types=1);

require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/MultiTenant/TenantManager.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/../src/TenantDB.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/ContractTemplate.php';
require_once __DIR__ . '/../src/ContractModule.php';
require_once __DIR__ . '/../src/ActivityLog.php';
require_once __DIR__ . '/navigation.php';

AuthManager::requireAuth();
TenantManager::initialize();
requirePermission('contracts_edit');

$pdo = getPDO();

// Resolve workspace context
$companyId = null;
$companyRecord = null;
$workspaceParam = isset($_GET['workspace']) ? sanitizeText($_GET['workspace']) : null;
if ($workspaceParam) {
    $stmt = $pdo->prepare('SELECT * FROM companies WHERE username = ?');
    $stmt->execute([$workspaceParam]);
    $companyRecord = $stmt->fetch() ?: null;
    $companyId = $companyRecord['id'] ?? null;
}
if (!$companyId) {
    $companyId = TenantDB::getTenant();
    if ($companyId) {
        $stmt = $pdo->prepare('SELECT * FROM companies WHERE id = ?');
        $stmt->execute([$companyId]);
        $companyRecord = $stmt->fetch() ?: $companyRecord;
    }
}
if ($companyId) {
    TenantDB::setTenant((int) $companyId);
}

$companyDisplayName = $companyRecord['name'] ?? 'Workspace';
$workspaceSlug = $companyRecord['username'] ?? $workspaceParam;
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode((string) $workspaceSlug) : '';
$workspaceQueryAmp = $workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '';

$templateId = (int) ($_GET['id'] ?? 0);
$template = $templateId > 0 ? ContractTemplate::find($templateId) : null;

if (!$template) {
    http_response_code(404);
    echo 'Contract template not found';
    exit;
}

$errors = [];
$successMessage = $_GET['success'] ?? null;

// Handle form submissions
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'attach_modules') {
        $moduleIds = array_map('intval', $_POST['module_ids'] ?? []);
        $moduleIds = array_values(array_filter($moduleIds, static fn (int $id): bool => $id > 0));

        if (!$moduleIds) {
            $errors[] = 'Select at least one module to attach.';
        } else {
            $currentModules = ContractTemplate::getModules($templateId);
            $maxSort = -1;
            foreach ($currentModules as $module) {
                $candidate = (int) ($module['sort_order'] ?? 0);
                if ($candidate > $maxSort) {
                    $maxSort = $candidate;
                }
            }
            foreach ($moduleIds as $offset => $moduleId) {
                ContractTemplate::attachModule($templateId, $moduleId, $maxSort + 1 + $offset);
            }

            try {
                $companyIdForLog = (int) ($template['company_id'] ?? 0);
                if ($companyIdForLog > 0) {
                    $currentUser = AuthManager::getCurrentUser();
                    $userId = $currentUser['id'] ?? null;
                    ActivityLog::log(
                        $companyIdForLog,
                        $userId ? (int) $userId : null,
                        'contract_template_modules_attached',
                        'contract_template',
                        $templateId,
                        $template['name'] ?? null,
                        null,
                        ['module_ids' => $moduleIds]
                    );
                }
            } catch (Throwable $e) {
                // ignore logging failures
            }

            redirect('/contract_template_modules.php', [
                'id' => $templateId,
                'success' => 'Modules attached to template.',
                'workspace' => $workspaceSlug,
            ]);
        }
    }

    if ($action === 'detach_module') {
        $moduleId = (int) ($_POST['module_id'] ?? 0);
        if ($moduleId > 0) {
            ContractTemplate::detachModule($templateId, $moduleId);
            redirect('/contract_template_modules.php', [
                'id' => $templateId,
                'success' => 'Module detached from template.',
                'workspace' => $workspaceSlug,
            ]);
        }
        $errors[] = 'Invalid module selected for removal.';
    }

    if ($action === 'reorder') {
        $moduleOrder = $_POST['module_order'] ?? '';
        header('Content-Type: application/json');
        if (!$moduleOrder) {
            echo json_encode(['error' => 'No module order data received.']);
            exit;
        }
        $orderArray = json_decode($moduleOrder, true);
        if (!is_array($orderArray)) {
            echo json_encode(['error' => 'Invalid module order format.']);
            exit;
        }
        $orderArray = array_values(array_filter(array_map('intval', $orderArray), static fn (int $id): bool => $id > 0));
        try {
            ContractTemplate::updateModuleOrder($templateId, $orderArray);
            echo json_encode(['success' => true]);
            exit;
        } catch (Throwable $e) {
            echo json_encode(['error' => 'Failed to update order.']);
            exit;
        }
    }
}

$attachedModules = ContractTemplate::getModules($templateId);
$availableModules = ContractTemplate::getAvailableModules($templateId);

$attachedModuleCount = count($attachedModules);
$availableModuleCount = count($availableModules);
$totalModuleCount = $attachedModuleCount + $availableModuleCount;

// Theme (dark by default)
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= h($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Contract Template Modules · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<body>
<?php renderNavigationNew('Contracts', $currentTheme); ?>

<div class="main-container">
    <?php
    require_once __DIR__ . '/components/headers/page-header.php';

    $actions = [
        [
            'label' => 'All contract templates',
            'url' => '/contract_templates.php',
            'type' => 'secondary',
            'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z',
            'append_workspace' => true,
        ],
        [
            'label' => 'Preview template',
            'url' => '/contract_template_preview.php?id=' . (int) $templateId,
            'type' => 'secondary',
            'icon' => 'M15 12a3 3 0 11-6 0 3 3 0 016 0z',
            'append_workspace' => true,
        ],
        [
            'label' => 'Edit template',
            'url' => '/contract_templates.php?edit=' . (int) $templateId . '#template-builder',
            'type' => 'secondary',
            'icon' => 'M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z',
            'append_workspace' => true,
        ],
    ];

    renderPageHeader(
        breadcrumbs: [
            ['label' => htmlspecialchars($companyDisplayName), 'url' => '/index.php', 'icon' => 'M3 7h18M3 12h18M3 17h18'],
            ['label' => 'Contract templates', 'url' => '/contract_templates.php', 'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z'],
        ],
        currentPage: 'Manage modules',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container">
        <?php if ($successMessage): ?>
            <div class="dash-section">
                <div class="status-banner success">
                    <span><?= h($successMessage) ?></span>
                </div>
            </div>
        <?php endif; ?>

        <?php if ($errors): ?>
            <div class="dash-section">
                <div class="status-banner error">
                    <div>
                        <?php foreach ($errors as $error): ?>
                            <p><?= h($error) ?></p>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>

        <div class="dash-section">
            <section class="card template-hero">
                <div>
                    <p class="section-title">Contract template modules</p>
                    <h1 class="template-hero__title">Manage modules for <?= h($template['name'] ?? 'Template') ?></h1>
                    <p class="template-hero__subtitle">Attach reusable blocks, reorder them, and enable/disable optional content for contract generation.</p>
                </div>
                <div class="template-hero__meta">
                    <span class="status-chip"><?= $attachedModuleCount ?> attached</span>
                    <span class="status-chip"><?= $availableModuleCount ?> available</span>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card template-stats">
                <div class="template-stats-grid">
                    <div class="template-stat">
                        <p class="template-stat__label">Attached modules</p>
                        <p class="template-stat__value"><?= $attachedModuleCount ?></p>
                        <p class="template-stat__hint">Drag to reorder</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Available modules</p>
                        <p class="template-stat__value"><?= $availableModuleCount ?></p>
                        <p class="template-stat__hint">Ready to attach</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Library size</p>
                        <p class="template-stat__value"><?= $totalModuleCount ?></p>
                        <p class="template-stat__hint">Total blocks</p>
                    </div>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card">
                <div>
                    <p class="section-title">Attached modules</p>
                    <p class="template-section-subtitle">Drag cards to reorder. Changes save immediately.</p>
                </div>

                <?php if (!$attachedModules): ?>
                    <div class="empty-state">
                        <h3>No modules attached yet</h3>
                        <p>Add modules below to get started.</p>
                    </div>
                <?php else: ?>
                    <div id="sortable-modules" class="module-stack">
                        <?php foreach ($attachedModules as $index => $module): ?>
                            <?php
                            $moduleId = (int) ($module['id'] ?? 0);
                            $moduleName = (string) ($module['name'] ?? 'Module');
                            $moduleCategory = (string) ($module['category'] ?? 'general');
                            $moduleBody = (string) ($module['description'] ?? ($module['content_html'] ?? ''));
                            $moduleWordCount = max(1, str_word_count(strip_tags($moduleBody)));
                            ?>
                            <article
                                class="module-card module-item"
                                data-module-id="<?= $moduleId ?>"
                                draggable="true"
                            >
                                <div class="module-card__head">
                                    <div class="module-card__head-left">
                                        <div class="module-drag-handle" aria-hidden="true" title="Drag to reorder" draggable="true">
                                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path>
                                            </svg>
                                        </div>
                                        <div>
                                            <p class="eyebrow">
                                                <span class="module-card__category"><?= h(ucfirst($moduleCategory)) ?></span>
                                                Module <?= $index + 1 ?>
                                            </p>
                                            <div class="module-card__title-row">
                                                <h3><?= h($moduleName) ?></h3>
                                                <?php if ((int) ($module['is_active'] ?? 0) === 1): ?>
                                                    <span class="status-chip">Default</span>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <span class="module-card__stat"><?= $moduleWordCount ?> words</span>
                                </div>

                                <div class="module-card__actions">
                                    <span class="module-card__hint">Drag the handle to adjust position.</span>
                                    <div class="card-actions">
                                        <form method="POST" class="inline" onsubmit="return confirm('Remove this module from template?');" action="/contract_template_modules.php<?= $workspaceQueryAmp ? ('?id=' . (int) $templateId . $workspaceQueryAmp) : ('?id=' . (int) $templateId) ?>">
                                            <input type="hidden" name="action" value="detach_module">
                                            <input type="hidden" name="module_id" value="<?= $moduleId ?>">
                                            <button type="submit" class="btn-icon btn-icon--danger" aria-label="Remove module">
                                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                                </svg>
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </article>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>
        </div>

        <div class="dash-section">
            <section class="card">
                <div>
                    <p class="section-title">Available modules</p>
                    <p class="template-section-subtitle">Select modules to attach to this template.</p>
                </div>

                <?php if (!$availableModules): ?>
                    <div class="empty-state">
                        <h3>All modules are attached</h3>
                        <p>This template already includes every module in your library.</p>
                    </div>
                <?php else: ?>
                    <form method="POST" action="/contract_template_modules.php?id=<?= (int) $templateId ?><?= $workspaceQueryAmp ?>">
                        <input type="hidden" name="action" value="attach_modules">

                        <div class="module-choice-grid">
                            <?php foreach ($availableModules as $module): ?>
                                <?php
                                $moduleWordCount = max(1, str_word_count(strip_tags((string) ($module['description'] ?? ''))));
                                ?>
                                <label class="template-card__option module-choice">
                                    <input class="template-card__radio module-choice__input" type="checkbox" name="module_ids[]" value="<?= (int) $module['id'] ?>">
                                    <div class="template-card module-choice__card">
                                        <div class="template-card__top">
                                            <div class="template-card__icon module-choice__icon">
                                                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"></path>
                                                </svg>
                                            </div>
                                            <span class="template-card__check"></span>
                                        </div>
                                        <div class="template-card__body">
                                            <div class="module-choice__title-row">
                                                <h3><?= h($module['name'] ?? 'Module') ?></h3>
                                                <?php if ((int) ($module['is_active'] ?? 0) === 1): ?>
                                                    <span class="status-chip">Default</span>
                                                <?php endif; ?>
                                            </div>
                                            <p class="module-choice__meta"><?= h(ucfirst((string) ($module['category'] ?? 'general'))) ?> · <?= $moduleWordCount ?> words</p>
                                            <div class="module-choice__stats">
                                                <span>$<?= number_format((float) ($module['price'] ?? 0), 2) ?></span>
                                            </div>
                                        </div>
                                    </div>
                                </label>
                            <?php endforeach; ?>
                        </div>

                        <div class="template-builder-actions" style="justify-content: flex-end; margin-top: 16px;">
                            <button type="submit" class="btn-primary">Attach selected modules</button>
                        </div>
                    </form>
                <?php endif; ?>
            </section>
        </div>
    </div>
</div>

<script>
(function () {
    const sortable = document.getElementById('sortable-modules');
    if (!sortable) return;

    let dragging = null;
    let placeholder = null;

    function createPlaceholder() {
        const el = document.createElement('div');
        el.className = 'module-placeholder';
        return el;
    }

    function getOrder() {
        return Array.from(sortable.querySelectorAll('.module-item')).map((el) => Number(el.getAttribute('data-module-id'))).filter(Boolean);
    }

    async function saveOrder() {
        const form = new FormData();
        form.append('action', 'reorder');
        form.append('module_order', JSON.stringify(getOrder()));

        const res = await fetch(window.location.href, {
            method: 'POST',
            body: form,
            credentials: 'same-origin'
        });

        try {
            const json = await res.json();
            if (!res.ok || json.error) {
                throw new Error(json.error || 'Failed to save order');
            }
        } catch (e) {
            // ignore
        }
    }

    sortable.addEventListener('dragstart', (e) => {
        const handle = e.target.closest('.module-drag-handle');
        if (!handle) {
            e.preventDefault();
            return;
        }

        const item = handle.closest('.module-item');
        if (!item) return;
        dragging = item;
        placeholder = createPlaceholder();
        e.dataTransfer.effectAllowed = 'move';
        e.dataTransfer.setData('text/plain', item.getAttribute('data-module-id') || '');
        item.classList.add('is-dragging');
    });

    sortable.addEventListener('dragover', (e) => {
        if (!dragging) return;
        e.preventDefault();
        const after = e.target.closest('.module-item');
        if (!after || after === dragging) return;
        const rect = after.getBoundingClientRect();
        const next = (e.clientY - rect.top) > rect.height / 2;

        if (!placeholder.parentNode) {
            sortable.insertBefore(placeholder, after);
        }

        sortable.insertBefore(placeholder, next ? after.nextSibling : after);
    });

    sortable.addEventListener('drop', async (e) => {
        if (!dragging || !placeholder) return;
        e.preventDefault();
        sortable.insertBefore(dragging, placeholder);
        placeholder.remove();
        placeholder = null;
        dragging.classList.remove('is-dragging');
        dragging = null;
        await saveOrder();
    });

    sortable.addEventListener('dragend', () => {
        if (placeholder) placeholder.remove();
        if (dragging) dragging.classList.remove('is-dragging');
        placeholder = null;
        dragging = null;
    });

    window.toggleModuleEnabled = async function (moduleId, enabled) {
        const form = new FormData();
        form.append('action', 'toggle_enabled');
        form.append('module_id', String(moduleId));
        form.append('enabled', enabled ? '1' : '0');

        const res = await fetch(window.location.href, {
            method: 'POST',
            body: form,
            credentials: 'same-origin'
        });

        const card = sortable.querySelector('.module-item[data-module-id="' + moduleId + '"]');
        if (card) {
            card.classList.toggle('module-card--disabled', !enabled);
        }

        try {
            const json = await res.json();
            if (!res.ok || json.error) {
                throw new Error(json.error || 'Failed');
            }
        } catch (e) {
            // ignore
        }
    };
})();
</script>

</body>
</html>
