<?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__ . '/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_view');

// Get action-specific permissions
$canCreateTemplate = hasPermission('templates_create');
$canEditTemplate = hasPermission('templates_edit');
$canDeleteTemplate = hasPermission('templates_delete');
$canManageTemplates = hasPermission('templates_manage');

// Resolve workspace context
$companyId = null;
$companyRecord = null;
$workspaceParam = isset($_GET['workspace']) ? sanitizeText($_GET['workspace']) : null;
$pdo = getPDO();
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;
    }
}
$companyDisplayName = $companyRecord['name'] ?? 'Selected workspace';
$workspaceSlug = $companyRecord['username'] ?? $workspaceParam;
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode($workspaceSlug) : '';

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

// Handle delete action
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete_template') {
    $templateId = (int) ($_POST['template_id'] ?? 0);
    if ($templateId > 0) {
        $oldTemplate = Template::find($templateId);
        Template::delete($templateId);

        // Log template deletion (best-effort)
        try {
            if ($companyId) {
                $currentUser = AuthManager::getCurrentUser();
                $userId = $currentUser['id'] ?? null;
                ActivityLog::log(
                    (int) $companyId,
                    $userId ? (int) $userId : null,
                    'template_deleted',
                    'template',
                    $templateId,
                    $oldTemplate['name'] ?? null,
                    $oldTemplate,
                    null
                );
            }
        } catch (Throwable $e) {
            // ignore logging failures
        }
        $workspaceParam = isset($_GET['workspace']) ? '&workspace=' . urlencode($_GET['workspace']) : '';
        header('Location: /templates.php?success=Template deleted successfully.' . $workspaceParam);
        exit;
    }
}

$templates = Template::all();
$successMessage = $_GET['success'] ?? null;
$totalTemplates = count($templates);
$templatesThisMonth = 0;
$latestUpdatedAt = null;
if ($templates) {
    $currentMonthStart = (new DateTime('first day of this month 00:00:00'))->format('Y-m-d H:i:s');
    foreach ($templates as $template) {
        if (!empty($template['created_at']) && $template['created_at'] >= $currentMonthStart) {
            $templatesThisMonth++;
        }
        if (!empty($template['updated_at'])) {
            if (!$latestUpdatedAt || $template['updated_at'] > $latestUpdatedAt) {
                $latestUpdatedAt = $template['updated_at'];
            }
        } elseif (!empty($template['created_at'])) {
            if (!$latestUpdatedAt || $template['created_at'] > $latestUpdatedAt) {
                $latestUpdatedAt = $template['created_at'];
            }
        }
    }
}
$latestUpdatedAtLabel = $latestUpdatedAt ? date('M j, Y', strtotime($latestUpdatedAt)) : 'No templates yet';

// Theme (dark by default for compatibility with the dashboard shell)
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= htmlspecialchars($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Templates · 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('Templates', $currentTheme); ?>

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

    $actions = [];
    if ($canCreateTemplate) {
        $actions[] = [
            'label' => 'New template',
            'url' => '/template_create.php',
            'type' => 'primary',
            'icon' => 'M12 4v16m8-8H4',
            'append_workspace' => true,
        ];
    }

    $actions[] = [
        'label' => 'Generate proposal',
        'url' => '/generate.php',
        'type' => 'secondary',
        'icon' => 'M12 4v16m8-8H4',
        'append_workspace' => true,
    ];

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

        <div class="dash-section">
            <section class="card template-hero">
                <div>
                    <p class="section-title">Templates</p>
                    <h1 class="template-hero__title">Reusable building blocks for <?= htmlspecialchars($companyDisplayName) ?></h1>
                    <p class="template-hero__subtitle">Launch proposals faster with pre-approved sections, brand styles, and reusable pricing modules.</p>
                </div>
                <div class="template-hero__meta">
                    <span class="status-chip"><?= $totalTemplates ?> total</span>
                    <?php if ($canCreateTemplate): ?>
                        <a href="/template_create.php<?= $workspaceQuery ?>" class="btn-primary">New template</a>
                    <?php endif; ?>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card">
                <div>
                    <p class="section-title">Snapshot</p>
                    <p class="template-section-subtitle">Quick pulse on template activity</p>
                </div>
                <div class="template-stats-grid">
                    <div class="template-stat">
                        <p class="template-stat__label">Total templates</p>
                        <p class="template-stat__value"><?= $totalTemplates ?></p>
                        <p class="template-stat__hint">Active in this workspace</p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Created this month</p>
                        <p class="template-stat__value"><?= $templatesThisMonth ?></p>
                        <p class="template-stat__hint">Since <?= date('M 1') ?></p>
                    </div>
                    <div class="template-stat">
                        <p class="template-stat__label">Last updated</p>
                        <p class="template-stat__value"><?= h($latestUpdatedAtLabel) ?></p>
                        <p class="template-stat__hint">Latest revision date</p>
                    </div>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <section class="card">
                <div class="template-library__header">
                    <div>
                        <p class="section-title">Template library</p>
                        <p class="template-section-subtitle">Design-ready proposals to duplicate and edit</p>
                    </div>
                </div>

                <?php if ($templates): ?>
                    <div class="template-library-grid">
                        <?php foreach ($templates as $template): ?>
                            <div class="template-library-card">
                                <div class="template-library-card__top">
                                    <div>
                                        <h3 class="template-library-card__title"><?= h($template['name']) ?></h3>
                                        <p class="template-library-card__meta">Updated <?= h(date('M j, Y', strtotime($template['updated_at'] ?? $template['created_at']))) ?></p>
                                    </div>
                                    <span class="status-chip">Template</span>
                                </div>
                                <div class="template-library-card__details">
                                    <span><?= $template['modules_count'] ?? 'Modular' ?></span>
                                    <span><?= !empty($template['created_by_name']) ? 'By ' . h($template['created_by_name']) : '' ?></span>
                                </div>
                                <div class="template-library-card__actions">
                                    <div class="template-library-card__actions-left">
                                        <a href="/template_preview.php?id=<?= (int) $template['id'] ?><?= $workspaceQuery ? '&workspace=' . urlencode($workspaceSlug) : '' ?>" class="btn-secondary btn-sm">Preview</a>
                                        <?php if ($canEditTemplate || $canManageTemplates): ?>
                                            <a href="/template_create.php?id=<?= (int) $template['id'] ?><?= $workspaceQuery ? '&workspace=' . urlencode($workspaceSlug) : '' ?>" class="btn-secondary btn-sm">Edit</a>
                                        <?php endif; ?>
                                        <a href="/template_edit_modules.php?id=<?= (int) $template['id'] ?><?= $workspaceQuery ? '&workspace=' . urlencode($workspaceSlug) : '' ?>" class="btn-secondary btn-sm">Modules</a>
                                    </div>
                                    <?php if ($canDeleteTemplate): ?>
                                        <form method="POST" onsubmit="return confirm('Delete this template?');">
                                            <input type="hidden" name="action" value="delete_template">
                                            <input type="hidden" name="template_id" value="<?= (int) $template['id'] ?>">
                                            <button type="submit" class="btn-danger btn-sm">Delete</button>
                                        </form>
                                    <?php endif; ?>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php else: ?>
                    <div class="empty-state">
                        <div class="empty-icon">
                            <svg fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="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"></path>
                            </svg>
                        </div>
                        <h3 class="empty-title">No templates yet</h3>
                        <p class="empty-desc">Set up your first template to standardize proposals across the team.</p>
                        <?php if ($canCreateTemplate): ?>
                            <a href="/template_create.php<?= $workspaceQuery ?>" class="btn-primary">Create your first template</a>
                        <?php endif; ?>
                    </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>

