<?php

declare(strict_types=1);

require_once __DIR__ . '/db.php';
require_once __DIR__ . '/TenantDB.php';

class TemplateModule
{
    public static function forTemplate(int $templateId): array
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('SELECT tm.*, m.title, m.content_html, m.default_required FROM template_modules tm JOIN modules m ON m.id = tm.module_id WHERE tm.template_id = :template_id AND tm.company_id = :company_id ORDER BY tm.sort_order ASC');
        $stmt->execute([':template_id' => $templateId, ':company_id' => $companyId]);

        return $stmt->fetchAll();
    }

    public static function attachedModuleIds(int $templateId): array
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('SELECT module_id FROM template_modules WHERE template_id = :template_id AND company_id = :company_id');
        $stmt->execute([':template_id' => $templateId, ':company_id' => $companyId]);

        return array_map('intval', array_column($stmt->fetchAll(), 'module_id'));
    }

    public static function attach(int $templateId, int $moduleId): void
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        
        if ($companyId === null) {
            throw new RuntimeException('Company ID not available. Workspace context not properly initialized.');
        }
        
        // Verify template exists and belongs to current workspace
        $stmt = $pdo->prepare('SELECT id FROM templates WHERE id = :template_id AND company_id = :company_id');
        $stmt->execute([':template_id' => $templateId, ':company_id' => $companyId]);
        if (!$stmt->fetch()) {
            throw new RuntimeException('Template not found.');
        }
        
        // Verify module exists and belongs to current workspace
        $stmt = $pdo->prepare('SELECT id FROM modules WHERE id = :module_id AND company_id = :company_id');
        $stmt->execute([':module_id' => $moduleId, ':company_id' => $companyId]);
        if (!$stmt->fetch()) {
            throw new RuntimeException('Module not found.');
        }
        
        // Check if already attached
        $stmt = $pdo->prepare('SELECT COUNT(*) FROM template_modules WHERE template_id = :template_id AND module_id = :module_id AND company_id = :company_id');
        $stmt->execute([':template_id' => $templateId, ':module_id' => $moduleId, ':company_id' => $companyId]);
        
        if ((int) $stmt->fetchColumn() === 0) {
            // Get next sort order
            $stmt = $pdo->prepare('SELECT MAX(sort_order) AS max_sort FROM template_modules WHERE template_id = :template_id AND company_id = :company_id');
            $stmt->execute([':template_id' => $templateId, ':company_id' => $companyId]);
            $maxSort = (int) ($stmt->fetch()['max_sort'] ?? 0);
            
            $stmt = $pdo->prepare('INSERT INTO template_modules (template_id, module_id, sort_order, company_id) VALUES (:template_id, :module_id, :sort_order, :company_id)');
            $stmt->execute([
                ':template_id' => $templateId,
                ':module_id' => $moduleId,
                ':sort_order' => $maxSort + 1,
                ':company_id' => $companyId,
            ]);
        }
    }

    public static function detach(int $templateModuleId): void
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('SELECT template_id FROM template_modules WHERE id = :id AND company_id = :company_id');
        $stmt->execute([':id' => $templateModuleId, ':company_id' => $companyId]);
        $templateId = $stmt->fetchColumn();

        if ($templateId) {
            $pdo->prepare('DELETE FROM template_modules WHERE id = :id AND company_id = :company_id')->execute([':id' => $templateModuleId, ':company_id' => $companyId]);
            self::reorder($templateId);
        }
    }

    public static function move(int $templateModuleId, string $direction): void
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('SELECT * FROM template_modules WHERE id = :id AND company_id = :company_id');
        $stmt->execute([':id' => $templateModuleId, ':company_id' => $companyId]);
        $currentModule = $stmt->fetch();

        if (!$currentModule) {
            return;
        }

        $comparison = $direction === 'up' ? '<' : '>';
        $order = $direction === 'up' ? 'DESC' : 'ASC';
        
        $stmt = $pdo->prepare("SELECT * FROM template_modules WHERE template_id = :template_id AND sort_order $comparison :sort_order AND company_id = :company_id ORDER BY sort_order $order LIMIT 1");
        $stmt->execute([
            ':template_id' => $currentModule['template_id'],
            ':sort_order' => $currentModule['sort_order'],
            ':company_id' => $companyId,
        ]);
        $targetModule = $stmt->fetch();

        if ($targetModule) {
            $update = $pdo->prepare('UPDATE template_modules SET sort_order = :sort_order WHERE id = :id AND company_id = :company_id');
            $update->execute([':sort_order' => $targetModule['sort_order'], ':id' => $templateModuleId, ':company_id' => $companyId]);
            $update->execute([':sort_order' => $currentModule['sort_order'], ':id' => $targetModule['id'], ':company_id' => $companyId]);
        }
    }

    public static function reorder(int $templateId): void
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('SELECT id FROM template_modules WHERE template_id = :template_id AND company_id = :company_id ORDER BY sort_order ASC, id ASC');
        $stmt->execute([':template_id' => $templateId, ':company_id' => $companyId]);
        $modules = $stmt->fetchAll();

        $update = $pdo->prepare('UPDATE template_modules SET sort_order = :sort_order WHERE id = :id AND company_id = :company_id');
        foreach ($modules as $index => $module) {
            $update->execute([':sort_order' => $index + 1, ':id' => $module['id'], ':company_id' => $companyId]);
        }
    }

    public static function reorderModules(int $templateId, array $moduleIds): void
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        
        if ($companyId === null) {
            throw new RuntimeException('Company ID not available. Workspace context not properly initialized.');
        }
        
        // Verify template exists and belongs to current workspace
        $stmt = $pdo->prepare('SELECT id FROM templates WHERE id = :template_id AND company_id = :company_id');
        $stmt->execute([':template_id' => $templateId, ':company_id' => $companyId]);
        if (!$stmt->fetch()) {
            throw new RuntimeException('Template not found. Please try again.');
        }
        
        foreach ($moduleIds as $sortOrder => $moduleId) {
            $update = $pdo->prepare('UPDATE template_modules SET sort_order = :sort_order WHERE template_id = :template_id AND module_id = :module_id AND company_id = :company_id');
            $update->execute([
                ':sort_order' => $sortOrder + 1,
                ':template_id' => $templateId,
                ':module_id' => $moduleId,
                ':company_id' => $companyId,
            ]);
        }
    }
}