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

// Require authentication
AuthManager::requireAuth();

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

// Check permission - Proposal modules require proposals_edit permission
requirePermission('proposals_edit');

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

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

$companyDisplayName = $company['name'] ?? 'Selected workspace';
$workspaceSlug = $workspaceParam
    ?? ($company['username'] ?? ($companyId ? (string) $companyId : null));
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode((string) $workspaceSlug) : '';
$workspaceQueryAmp = $workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '';

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

$defaults = [
    'title' => '',
    'content_html' => '',
    'default_required' => 0,
];

$formDataCreate = $defaults;
$formDataEdit = $defaults;
$editingModule = null;

if (isset($_GET['edit'])) {
    $editId = (int) $_GET['edit'];
    if ($editId > 0) {
        $editingModule = Module::find($editId);
        if ($editingModule) {
            $formDataEdit = array_merge($formDataEdit, $editingModule);
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'create') {
        $formDataCreate = [
            'title' => sanitizeText($_POST['title'] ?? ''),
            'content_html' => $_POST['content_html'] ?? '',
            'default_required' => isset($_POST['default_required']) ? 1 : 0,
        ];

        if ($formDataCreate['title'] === '') {
            $errors[] = 'Module title is required.';
        }

        if (!$errors) {
            $newModuleId = Module::create($formDataCreate);

            // Log proposal module creation (best-effort)
            try {
                if ($companyId) {
                    $currentUser = AuthManager::getCurrentUser();
                    $userId = $currentUser['id'] ?? null;
                    ActivityLog::log(
                        (int) $companyId,
                        $userId ? (int) $userId : null,
                        'template_created',
                        'proposal_module',
                        (int) $newModuleId,
                        $formDataCreate['title'] ?? null,
                        null,
                        $formDataCreate
                    );
                }
            } catch (Throwable $e) {
                // ignore logging failures
            }
            $redirectParams = ['success' => 'Module created successfully.'];
            if (isset($_GET['workspace'])) {
                $redirectParams['workspace'] = $_GET['workspace'];
            }
            redirect('/modules.php', $redirectParams);
        }
    }

    if ($action === 'update') {
        $moduleId = isset($_POST['id']) ? (int) $_POST['id'] : 0;
        $oldModule = $moduleId > 0 ? Module::find($moduleId) : null;
        $formDataEdit = [
            'title' => sanitizeText($_POST['title'] ?? ''),
            'content_html' => $_POST['content_html'] ?? '',
            'default_required' => isset($_POST['default_required']) ? 1 : 0,
        ];

        if ($formDataEdit['title'] === '') {
            $errors[] = 'Module title is required.';
        }

        if ($moduleId <= 0) {
            $errors[] = 'Invalid module selected for update.';
        }

        if (!$errors && $moduleId > 0) {
            Module::update($moduleId, $formDataEdit);

            // Log proposal module update (best-effort)
            try {
                if ($companyId) {
                    $currentUser = AuthManager::getCurrentUser();
                    $userId = $currentUser['id'] ?? null;
                    ActivityLog::log(
                        (int) $companyId,
                        $userId ? (int) $userId : null,
                        'template_updated',
                        'proposal_module',
                        $moduleId,
                        $formDataEdit['title'] ?? null,
                        $oldModule,
                        $formDataEdit
                    );
                }
            } catch (Throwable $e) {
                // ignore logging failures
            }
            $redirectParams = ['success' => 'Module updated successfully.'];
            if (isset($_GET['workspace'])) {
                $redirectParams['workspace'] = $_GET['workspace'];
            }
            redirect('/modules.php', $redirectParams);
        }
    }

    if ($action === 'delete') {
        $moduleId = isset($_POST['id']) ? (int) $_POST['id'] : 0;
        if ($moduleId > 0) {
            $oldModule = Module::find($moduleId);
            Module::delete($moduleId);

            // Log proposal module deletion (best-effort)
            try {
                if ($companyId) {
                    $currentUser = AuthManager::getCurrentUser();
                    $userId = $currentUser['id'] ?? null;
                    ActivityLog::log(
                        (int) $companyId,
                        $userId ? (int) $userId : null,
                        'template_deleted',
                        'proposal_module',
                        $moduleId,
                        $oldModule['title'] ?? null,
                        $oldModule,
                        null
                    );
                }
            } catch (Throwable $e) {
                // ignore logging failures
            }
            $redirectParams = ['success' => 'Module deleted.'];
            if (isset($_GET['workspace'])) {
                $redirectParams['workspace'] = $_GET['workspace'];
            }
            redirect('/modules.php', $redirectParams);
        }

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

$modules = Module::all();
$moduleCount = count($modules);
$defaultIncludedCount = 0;
$latestModuleTimestamp = null;

foreach ($modules as $moduleItem) {
    if (!empty($moduleItem['default_required'])) {
        $defaultIncludedCount++;
    }

    $candidate = $moduleItem['updated_at'] ?? $moduleItem['created_at'] ?? null;
    if ($candidate) {
        $candidateTimestamp = strtotime((string) $candidate);
        if ($candidateTimestamp && (!$latestModuleTimestamp || $candidateTimestamp > $latestModuleTimestamp)) {
            $latestModuleTimestamp = $candidateTimestamp;
        }
    }
}

$latestModuleLabel = $latestModuleTimestamp ? date('M j, Y', $latestModuleTimestamp) : 'No modules yet';
// Theme (dark by default)
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';

$tinymceComponent = __DIR__ . '/components/editors/tinymce-init.php';
if (file_exists($tinymceComponent)) {
    require_once $tinymceComponent;
}

$variableTokens = function_exists('getTinyMCEVariableTokens') ? getTinyMCEVariableTokens() : [
    ['label' => 'Client name', 'token' => '{{client_name}}'],
    ['label' => 'Company', 'token' => '{{company_name}}'],
    ['label' => 'Project', 'token' => '{{project_name}}'],
    ['label' => 'Proposal date', 'token' => '{{proposal_date}}'],
    ['label' => 'Client email', 'token' => '{{client_email}}'],
    ['label' => 'Client phone', 'token' => '{{client_phone}}'],
    ['label' => 'Client address', 'token' => '{{client_address}}'],
];
?>
<!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>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://cdn.jsdelivr.net/npm/tinymce@6.8.2/tinymce.min.js"></script>
    <?php if (function_exists('renderTinyMCEInit')) { renderTinyMCEInit(); } ?>
    <script>
        function insertVariable(variable) {
            if (window.tinymce && tinymce.activeEditor) {
                tinymce.activeEditor.insertContent(variable);
            }
        }
    </script>
</head>
<?php require_once __DIR__ . '/components/headers/page-header.php'; ?>
<body>
<?php renderNavigationNew('Modules', $currentTheme); ?>

<div class="main-container">
    <?php
    $actions = [
        [
            'label' => 'Templates',
            'url' => '/templates.php' . $workspaceQuery,
            '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',
        ],
        [
            'label' => 'Generate proposal',
            'url' => '/generate.php' . $workspaceQuery,
            'type' => 'primary',
            'icon' => 'M12 4v16m8-8H4',
        ],
    ];

    renderPageHeader(
        breadcrumbs: [
            ['label' => htmlspecialchars($companyDisplayName), 'url' => '/index.php' . $workspaceQuery, 'icon' => 'M3 7h18M3 12h18M3 17h18'],
            ['label' => 'Proposals', 'url' => '/proposals.php' . $workspaceQuery, '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: 'Modules',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container proposal-wizard">
        <?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">Proposal modules</p>
                    <h1 class="template-hero__title">Module library for <?= htmlspecialchars($companyDisplayName) ?></h1>
                    <p class="template-hero__subtitle">Create reusable content blocks once, then attach them to templates and proposals without copy-paste.</p>
                </div>
                <div class="template-hero__meta">
                    <span class="status-chip"><?= $moduleCount ?> total</span>
                    <span class="status-chip"><?= $defaultIncludedCount ?> auto-included</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">Total modules</p>
                        <p class="template-stat__value"><?= $moduleCount ?></p>
                        <p class="template-stat__hint">Available to every template</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Auto-included</p>
                        <p class="template-stat__value"><?= $defaultIncludedCount ?></p>
                        <p class="template-stat__hint">Default when attaching modules</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Last updated</p>
                        <p class="template-stat__value"><?= h($latestModuleLabel) ?></p>
                        <p class="template-stat__hint">Most recent module activity</p>
                    </div>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card template-builder-card" id="module-form">
                <div class="template-builder-form">
                    <form method="POST" class="space-y-5">
                        <input type="hidden" name="action" value="<?= $editingModule ? 'update' : 'create' ?>">
                        <?php if ($workspaceSlug): ?>
                            <input type="hidden" name="workspace" value="<?= h($workspaceSlug) ?>">
                        <?php endif; ?>
                        <?php if ($editingModule): ?>
                            <input type="hidden" name="id" value="<?= (int) $editingModule['id'] ?>">
                        <?php endif; ?>

                        <label class="form-field">
                            <span>Module title *</span>
                            <input
                                type="text"
                                name="title"
                                value="<?= h($editingModule ? $formDataEdit['title'] : $formDataCreate['title']) ?>"
                                class="field-input"
                                required
                                placeholder="e.g. Scope overview"
                            >
                        </label>

                        <div class="template-editor-block">
                            <div class="template-editor-block__head">
                                <div>
                                    <p class="template-editor-block__title">Module content</p>
                                    <p class="template-editor-block__subtitle">This block can be attached to templates and rendered with variables.</p>
                                </div>
                            </div>
                            <?php if (function_exists('renderTinyMCEVariableInserts')) { renderTinyMCEVariableInserts($variableTokens); } ?>
                            <textarea
                                name="content_html"
                                id="module_content"
                                class="editor-area rich"
                                rows="10"
                            ><?= h($editingModule ? $formDataEdit['content_html'] : $formDataCreate['content_html']) ?></textarea>
                        </div>

                        <label class="checkbox-field">
                            <input type="checkbox" name="default_required" value="1" <?= ($editingModule ? $formDataEdit['default_required'] : $formDataCreate['default_required']) ? 'checked' : '' ?>>
                            <span>Include by default whenever templates attach modules</span>
                        </label>

                        <div class="template-builder-actions">
                            <button type="submit" class="btn-primary">
                                <?= $editingModule ? 'Update module' : 'Create module' ?>
                            </button>
                            <?php if ($editingModule): ?>
                                <a href="/modules.php<?= $workspaceQuery ?>" class="btn-secondary">Cancel</a>
                            <?php endif; ?>
                        </div>
                    </form>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card">
                <div class="template-library__header">
                    <div>
                        <p class="section-title">Module library</p>
                        <p class="template-section-subtitle">Reusable blocks to attach to templates</p>
                    </div>
                </div>

                <?php if ($modules): ?>
                    <div class="template-library-grid">
                        <?php foreach ($modules as $module): ?>
                            <?php
                                $moduleId = (int) ($module['id'] ?? 0);
                                $editLink = '/modules.php?edit=' . $moduleId . ($workspaceSlug ? '&workspace=' . urlencode((string) $workspaceSlug) : '');
                                $moduleUpdated = $module['updated_at'] ?? $module['created_at'] ?? null;
                                $moduleUpdatedLabel = $moduleUpdated ? date('M j, Y', strtotime((string) $moduleUpdated)) : 'Recently';
                            ?>
                            <div class="template-library-card">
                                <div class="template-library-card__top">
                                    <div>
                                        <h3 class="template-library-card__title"><?= h($module['title'] ?? 'Untitled module') ?></h3>
                                        <p class="template-library-card__meta">Updated <?= h($moduleUpdatedLabel) ?></p>
                                    </div>
                                    <span class="status-chip"><?= !empty($module['default_required']) ? 'Auto-included' : 'Optional' ?></span>
                                </div>
                                <div class="template-library-card__details">
                                    <span>Module #<?= $moduleId ?></span>
                                    <span><?= !empty($module['default_required']) ? 'Default on attach' : '' ?></span>
                                </div>
                                <div class="template-library-card__actions">
                                    <div class="template-library-card__actions-left">
                                        <a href="<?= $editLink ?>" class="btn-secondary btn-sm">Edit</a>
                                    </div>
                                    <form method="POST" onsubmit="return confirm('Delete this module?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $moduleId ?>">
                                        <?php if ($workspaceSlug): ?>
                                            <input type="hidden" name="workspace" value="<?= h($workspaceSlug) ?>">
                                        <?php endif; ?>
                                        <button type="submit" class="btn-danger btn-sm">Delete</button>
                                    </form>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="empty-state">
                        <h3>No modules yet</h3>
                        <p>Create your first content block above.</p>
                    </div>
                <?php endif; ?>
            </section>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    if (mobileMenuBtn && typeof window.openAppSidebar === 'function') {
        mobileMenuBtn.addEventListener('click', window.openAppSidebar);
    }
});
</script>

</body>
</html>
