<?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/ActivityLog.php';
require_once __DIR__ . '/navigation.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/ContractModule.php';

// Require authentication
AuthManager::requireAuth();

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

// Check permission - Contract modules require contracts_edit permission
requirePermission('contracts_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;
    }
}

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' => '',
    'category' => 'legal',
    'sort_order' => 0,
    'default_required' => 0,
];

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

if (isset($_GET['edit'])) {
    $editId = (int) $_GET['edit'];
    if ($editId > 0) {
        $editingModule = ContractModule::find($editId);
        if ($editingModule) {
            // Map database fields to form field names
            $mappedData = [
                'title' => $editingModule['name'] ?? '',
                'content_html' => $editingModule['description'] ?? '',
                'category' => $editingModule['category'] ?? 'general',
                'sort_order' => 0, // Default since sort_order doesn't exist in DB
                'default_required' => $editingModule['is_active'] ?? 1,
                'price' => $editingModule['price'] ?? 0.00,
            ];
            $formDataEdit = array_merge($formDataEdit, $mappedData);
        }
    }
}

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

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

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

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

            // Log contract module creation (best-effort)
            try {
                $createdModule = ContractModule::find((int) $newModuleId);
                $companyId = (int) ($createdModule['company_id'] ?? 0);
                if ($companyId > 0) {
                    $currentUser = AuthManager::getCurrentUser();
                    $userId = $currentUser['id'] ?? null;
                    ActivityLog::log(
                        $companyId,
                        $userId ? (int) $userId : null,
                        'contract_module_created',
                        'contract_module',
                        (int) $newModuleId,
                        $formDataCreate['title'] ?? null,
                        null,
                        $formDataCreate
                    );
                }
            } catch (Throwable $e) {
                // ignore logging failures
            }
            $redirectParams = ['success' => 'Module created successfully.'];
            if ($workspaceSlug) {
                $redirectParams['workspace'] = $workspaceSlug;
            }
            redirect('/contract_modules.php', $redirectParams);
        }
    }

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

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

        if (!$errors) {
            ContractModule::update($moduleId, $formDataEdit);

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

    if ($action === 'delete' && isset($_POST['id'])) {
        $moduleId = (int) $_POST['id'];
        $oldModule = $moduleId > 0 ? ContractModule::find($moduleId) : null;
        ContractModule::delete($moduleId);
        
        // Log contract module deletion (best-effort)
        try {
            $companyId = (int) ($oldModule['company_id'] ?? 0);
            if ($companyId > 0) {
                $currentUser = AuthManager::getCurrentUser();
                $userId = $currentUser['id'] ?? null;
                ActivityLog::log(
                    $companyId,
                    $userId ? (int) $userId : null,
                    'contract_module_deleted',
                    'contract_module',
                    $moduleId,
                    $oldModule['title'] ?? null,
                    $oldModule,
                    null
                );
            }
        } catch (Throwable $e) {
            // ignore logging failures
        }
        $redirectParams = ['success' => 'Module deleted successfully.'];
        if ($workspaceSlug) {
            $redirectParams['workspace'] = $workspaceSlug;
        }
        redirect('/contract_modules.php', $redirectParams);
    }
}

$modules = ContractModule::all();
$categories = ContractModule::getCategories();

$moduleCount = count($modules);
$defaultIncludedCount = 0;
$latestModuleTimestamp = null;
foreach ($modules as $moduleItem) {
    if (!empty($moduleItem['is_active'])) {
        $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 = [
    ['label' => 'Client name', 'token' => '{{client_name}}'],
    ['label' => 'Company', 'token' => '{{company_name}}'],
    ['label' => 'Project', 'token' => '{{project_name}}'],
    ['label' => 'Contract date', 'token' => '{{contract_date}}'],
    ['label' => 'Contract number', 'token' => '{{contract_number}}'],
    ['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>Contract 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('Contracts', $currentTheme); ?>

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

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

        <!-- Header -->
        <div class="dash-section">
            <section class="card template-hero">
                <div>
                    <p class="section-title">Contract 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 contract templates.</p>
                </div>
                <div class="template-hero__meta">
                    <span class="status-chip"><?= $moduleCount ?> total</span>
                    <span class="status-chip"><?= $defaultIncludedCount ?> default</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">Reusable blocks</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Default included</p>
                        <p class="template-stat__value"><?= $defaultIncludedCount ?></p>
                        <p class="template-stat__hint">Enabled by default</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">
            <!-- Create Module -->
            <section class="card template-builder-card" id="module-form">
                <div class="template-builder-form">
                    <form method="POST" action="/contract_modules.php<?= $workspaceQuery ?>#module-form">
                        <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'] ?? 0) ?>">
                        <?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. Payment terms"
                            >
                        </label>

                        <div class="template-builder-grid" style="grid-template-columns: 1fr 1fr;">
                            <label class="form-field">
                                <span>Category</span>
                                <select name="category" class="field-input">
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?= h($category) ?>" <?= ($editingModule ? $formDataEdit['category'] : $formDataCreate['category']) === $category ? 'selected' : '' ?>>
                                            <?= h(ucfirst($category)) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </label>

                            <label class="form-field">
                                <span>Price</span>
                                <input
                                    type="number"
                                    name="price"
                                    step="0.01"
                                    value="<?= h((string) (($editingModule ? ($formDataEdit['price'] ?? 0) : ($formDataCreate['price'] ?? 0)))) ?>"
                                    class="field-input"
                                    placeholder="0.00"
                                >
                            </label>
                        </div>

                        <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 contract 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 when attaching modules to templates</span>
                        </label>

                        <div class="template-builder-actions">
                            <button type="submit" class="btn-primary">
                                <?= $editingModule ? 'Update module' : 'Create module' ?>
                            </button>
                            <?php if ($editingModule): ?>
                                <a href="/contract_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 contract templates</p>
                    </div>
                </div>

                <?php if ($modules): ?>
                    <div class="template-library-grid">
                        <?php foreach ($modules as $module): ?>
                            <?php
                            $moduleId = (int) ($module['id'] ?? 0);
                            $editLink = '/contract_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['name'] ?? 'Untitled module') ?></h3>
                                        <p class="template-library-card__meta">Updated <?= h($moduleUpdatedLabel) ?></p>
                                    </div>
                                    <span class="status-chip"><?= !empty($module['is_active']) ? 'Default' : 'Optional' ?></span>
                                </div>
                                <div class="template-library-card__details">
                                    <span>Module #<?= $moduleId ?></span>
                                    <span><?= h(ucfirst((string) ($module['category'] ?? 'general'))) ?> · $<?= number_format((float) ($module['price'] ?? 0), 2) ?></span>
                                </div>
                                <div class="template-library-card__actions">
                                    <div class="template-library-card__actions-left">
                                        <a href="<?= $editLink ?>#module-form" class="btn-secondary btn-sm">Edit</a>
                                    </div>
                                    <form method="POST" onsubmit="return confirm('Delete this module?');" action="/contract_modules.php<?= $workspaceQuery ?>">
                                        <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>
