<?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/TenantDB.php';
require_once __DIR__ . '/../src/Template.php';
require_once __DIR__ . '/../src/Module.php';
require_once __DIR__ . '/../src/TemplateModule.php';
require_once __DIR__ . '/navigation.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';
require_once __DIR__ . '/../src/ActivityLog.php';

// Require authentication
AuthManager::requireAuth();

// Initialize tenant context
TenantManager::initialize();

// Check permission
requirePermission('templates_edit');

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

// Set tenant context for Template class
if ($companyId) {
    TenantDB::setTenant($companyId);
}

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

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

// Workspace display context for breadcrumbs / links
$companyDisplayName = 'Selected workspace';
$workspaceSlug = null;
if ($companyId) {
    try {
        $pdo = getPDO();
        $stmt = $pdo->prepare('SELECT name, username FROM companies WHERE id = ?');
        $stmt->execute([$companyId]);
        if ($row = $stmt->fetch()) {
            $companyDisplayName = $row['name'] ?? $companyDisplayName;
            $workspaceSlug = $row['username'] ?? null;
        }
    } catch (Throwable $e) {
        // best-effort only
    }
}

if (!$workspaceSlug && isset($workspaceParam)) {
    $workspaceSlug = $workspaceParam;
}

$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode($workspaceSlug) : '';
$workspaceQueryAmp = $workspaceSlug ? '&workspace=' . urlencode($workspaceSlug) : '';

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $postedTemplateId = isset($_POST['template_id']) ? (int) $_POST['template_id'] : 0;

    if ($postedTemplateId !== $templateId) {
        $errors[] = 'Template mismatch. Please reload the page and try again.';
    }

    if (!$errors) {
        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 {
                foreach ($moduleIds as $moduleId) {
                    TemplateModule::attach($templateId, $moduleId);
                }

                // Log template modules attached (best-effort)
                try {
                    if ($companyId) {
                        $currentUser = AuthManager::getCurrentUser();
                        $userId = $currentUser['id'] ?? null;
                        ActivityLog::log(
                            (int) $companyId,
                            $userId ? (int) $userId : null,
                            'template_modules_attached',
                            'template',
                            $templateId,
                            $template['name'] ?? null,
                            null,
                            ['module_ids' => $moduleIds]
                        );
                    }
                } catch (Throwable $e) {
                    // ignore logging failures
                }

                $redirectParams = [
                    'id' => $templateId,
                    'success' => 'Modules attached to template.',
                ];
                if (isset($_GET['workspace'])) {
                    $redirectParams['workspace'] = $_GET['workspace'];
                }
                redirect('/template_edit_modules.php', $redirectParams);
            }
        }

        if ($action === 'detach_module') {
            $templateModuleId = isset($_POST['template_module_id']) ? (int) $_POST['template_module_id'] : 0;
            if ($templateModuleId > 0) {
                TemplateModule::detach($templateModuleId);

                // Log template module detachment (best-effort)
                try {
                    if ($companyId) {
                        $currentUser = AuthManager::getCurrentUser();
                        $userId = $currentUser['id'] ?? null;
                        ActivityLog::log(
                            (int) $companyId,
                            $userId ? (int) $userId : null,
                            'template_module_detached',
                            'template',
                            $templateId,
                            $template['name'] ?? null,
                            ['template_module_id' => $templateModuleId],
                            null
                        );
                    }
                } catch (Throwable $e) {
                    // ignore logging failures
                }
                $redirectParams = [
                    'id' => $templateId,
                    'success' => 'Module detached from template.',
                ];
                if (isset($_GET['workspace'])) {
                    $redirectParams['workspace'] = $_GET['workspace'];
                }
                redirect('/template_edit_modules.php', $redirectParams);
            }

            $errors[] = 'Invalid module selected for removal.';
        }

        if ($action === 'move_up' || $action === 'move_down') {
            $templateModuleId = isset($_POST['template_module_id']) ? (int) $_POST['template_module_id'] : 0;
            if ($templateModuleId > 0) {
                TemplateModule::move($templateModuleId, $action === 'move_up' ? 'up' : 'down');

                // Log template modules reordered (best-effort)
                try {
                    if ($companyId) {
                        $currentUser = AuthManager::getCurrentUser();
                        $userId = $currentUser['id'] ?? null;
                        ActivityLog::log(
                            (int) $companyId,
                            $userId ? (int) $userId : null,
                            'template_modules_reordered',
                            'template',
                            $templateId,
                            $template['name'] ?? null,
                            null,
                            [
                                'template_module_id' => $templateModuleId,
                                'direction' => $action === 'move_up' ? 'up' : 'down',
                            ]
                        );
                    }
                } catch (Throwable $e) {
                    // ignore logging failures
                }
                $redirectParams = [
                    'id' => $templateId,
                    'success' => 'Module order updated.',
                ];
                if (isset($_GET['workspace'])) {
                    $redirectParams['workspace'] = $_GET['workspace'];
                }
                redirect('/template_edit_modules.php', $redirectParams);
            }

            $errors[] = 'Invalid module selected for ordering.';
        }

        if ($action === 'reorder') {
            error_log('Reorder action - POST data: ' . json_encode($_POST));
            error_log('Reorder action - templateId from POST: ' . ($_POST['template_id'] ?? 'not set'));
            error_log('Reorder action - templateId from GET: ' . $templateId);
            
            $moduleOrder = $_POST['module_order'] ?? '';
            if ($moduleOrder) {
                $orderArray = json_decode($moduleOrder, true);
                if (is_array($orderArray)) {
                    try {
                        TemplateModule::reorderModules($templateId, $orderArray);
                        // Log template modules reordered (best-effort)
                        try {
                            if ($companyId) {
                                $currentUser = AuthManager::getCurrentUser();
                                $userId = $currentUser['id'] ?? null;
                                ActivityLog::log(
                                    (int) $companyId,
                                    $userId ? (int) $userId : null,
                                    'template_modules_reordered',
                                    'template',
                                    $templateId,
                                    $template['name'] ?? null,
                                    null,
                                    ['order' => $orderArray]
                                );
                            }
                        } catch (Throwable $e) {
                            // ignore logging failures
                        }
                        // Return JSON success for AJAX requests
                        header('Content-Type: application/json');
                        echo json_encode(['success' => 'Module order updated successfully.']);
                        exit;
                    } catch (Exception $e) {
                        error_log('Reorder error in template_edit_modules.php: ' . $e->getMessage());
                        // Return JSON error for AJAX requests
                        header('Content-Type: application/json');
                        echo json_encode(['error' => $e->getMessage()]);
                        exit;
                    }
                } else {
                    error_log('Reorder: Invalid module order format - moduleOrder: ' . $moduleOrder);
                    // Return JSON error for AJAX requests
                    header('Content-Type: application/json');
                    echo json_encode(['error' => 'Invalid module order format.']);
                    exit;
                }
            } else {
                error_log('Reorder: No module order data received');
                // Return JSON error for AJAX requests
                header('Content-Type: application/json');
                echo json_encode(['error' => 'No module order data received.']);
                exit;
            }
        }
    }
}

$allModules = Module::all();
$attachedModules = TemplateModule::forTemplate($templateId);
$attachedModuleIds = TemplateModule::attachedModuleIds($templateId);

$availableModules = array_filter($allModules, static function (array $module) use ($attachedModuleIds): bool {
    return !in_array((int) $module['id'], $attachedModuleIds, true);
});

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

// 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 Template Modules · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
</head>
<body>
<?php renderNavigationNew('Templates', $currentTheme); ?>

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

    $actions = [
        [
            'label' => 'All templates',
            'url' => '/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' => '/template_preview.php?id=' . (int) $template['id'],
            'type' => 'secondary',
            'icon' => 'M15 12a3 3 0 11-6 0 3 3 0 016 0z',
            'append_workspace' => true,
        ],
        [
            'label' => 'Edit template',
            'url' => '/template_create.php?id=' . (int) $template['id'],
            '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' => 'Templates', 'url' => '/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">Template modules</p>
                    <h1 class="template-hero__title">Manage modules for <?= h($template['name']) ?></h1>
                    <p class="template-hero__subtitle">Attach reusable blocks, reorder them, and keep required content consistent across proposals.</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 (empty($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 $moduleWordCount = max(1, str_word_count(strip_tags($module['content_html'] ?? ''))); ?>
                            <article class="module-card module-item" data-module-id="<?= (int) $module['module_id'] ?>">
                                <div class="module-card__head">
                                    <div class="module-card__head-left">
                                    <div class="module-drag-handle" aria-hidden="true" title="Drag to reorder">
                                            <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($module['category'] ?? 'general')) ?></span>
                                                Module <?= $index + 1 ?>
                                            </p>
                                            <div class="module-card__title-row">
                                                <h3><?= h($module['title']) ?></h3>
                                                <?php if ((int) $module['default_required'] === 1): ?>
                                                    <span class="status-chip active small">Required</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?');">
                                            <input type="hidden" name="action" value="detach_module">
                                            <input type="hidden" name="template_id" value="<?= (int) $template['id'] ?>">
                                            <input type="hidden" name="template_module_id" value="<?= (int) $module['id'] ?>">
                                            <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 (empty($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">
                        <input type="hidden" name="action" value="attach_modules">
                        <input type="hidden" name="template_id" value="<?= (int) $template['id'] ?>">

                        <div class="module-choice-grid">
                            <?php foreach ($availableModules as $module): ?>
                                <?php $moduleWordCount = max(1, str_word_count(strip_tags($module['content_html'] ?? ''))); ?>
                                <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="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path>
                                                </svg>
                                            </div>
                                            <span class="template-card__check"></span>
                                        </div>
                                        <div class="template-card__body">
                                            <div class="module-choice__title-row">
                                                <h3><?= h($module['title']) ?></h3>
                                                <?php if ((int) $module['default_required'] === 1): ?>
                                                    <span class="status-chip active small">Required</span>
                                                <?php endif; ?>
                                            </div>
                                            <p class="module-choice__meta">Category · <?= h(ucfirst($module['category'] ?? 'general')) ?></p>
                                        </div>
                                        <div class="module-choice__stats">
                                            <span><?= $moduleWordCount ?> words</span>
                                            <?php if (!empty($module['updated_at'])): ?>
                                                <span>Updated <?= h(date('M j', strtotime($module['updated_at']))) ?></span>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </label>
                            <?php endforeach; ?>
                        </div>

                        <div class="module-choice-actions">
                            <span class="card-subtitle"><?= count($availableModules) ?> available</span>
                            <button type="submit" class="btn-primary">Attach selected modules</button>
                        </div>
                    </form>
                <?php endif; ?>
            </section>
        </div>
    </div>
</div>

<script>
// Wire mobile menu button to app sidebar toggle from navigation.php
document.addEventListener('DOMContentLoaded', function () {
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    if (mobileMenuBtn && typeof window.openAppSidebar === 'function') {
        mobileMenuBtn.addEventListener('click', function () {
            window.openAppSidebar();
        });
    }
});

$(document).ready(function() {
    $("#sortable-modules").sortable({
        items: ".module-item",
        handle: ".module-drag-handle",
        placeholder: "module-placeholder",
        tolerance: "pointer",
        cursor: "move",
        opacity: 0.7,
        revert: false,
        update: function(event, ui) {
            var moduleOrder = [];
            $("#sortable-modules .module-item").each(function() {
                moduleOrder.push($(this).data("module-id"));
            });

            console.log('Reordering modules:', moduleOrder);
            console.log('Template ID being sent: <?= (int) $template['id'] ?>');
            console.log('Full POST data:', {
                action: "reorder",
                template_id: <?= (int) $template['id'] ?>,
                module_order: JSON.stringify(moduleOrder)
            });

            // Disable sortable temporarily to prevent conflicts
            $("#sortable-modules").sortable("disable");

            $.post("/template_edit_modules.php?id=<?= (int) $template['id'] ?><?= isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '' ?>", {
                action: "reorder",
                template_id: <?= (int) $template['id'] ?>,
                module_order: JSON.stringify(moduleOrder)
            }).done(function(response) {
                console.log('Reorder response:', response);
                // Check if response is JSON error
                if (typeof response === 'string' && response.indexOf('{') === 0) {
                    try {
                        var jsonResponse = JSON.parse(response);
                        if (jsonResponse.error) {
                            $("#sortable-modules").sortable("enable");
                            alert('Error reordering modules: ' + jsonResponse.error + '. Please try again.');
                            return;
                        }
                    } catch (e) {
                        // Not JSON, continue with reload
                    }
                }
                // Reload only after successful response
                location.reload();
            }).fail(function(xhr, status, error) {
                console.error('Reorder error:', {
                    status: status,
                    error: error,
                    response: xhr.responseText
                });
                // Try to parse JSON error
                var errorMessage = 'Unknown error occurred';
                try {
                    var jsonResponse = JSON.parse(xhr.responseText);
                    if (jsonResponse.error) {
                        errorMessage = jsonResponse.error;
                    }
                } catch (e) {
                    errorMessage = xhr.responseText || error;
                }
                // Re-enable sortable on error and show message
                $("#sortable-modules").sortable("enable");
                alert('Error reordering modules: ' + errorMessage + '. Please try again.');
            });
        }
    });
});

function toggleModule(moduleId, enabled) {
    $.post("/template_edit_modules.php?id=<?= (int) $template['id'] ?><?= isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '' ?>", {
        action: "toggle_module",
        module_id: moduleId,
        enabled: enabled
    });
}
</script>
</body>
</html>
