<?php

declare(strict_types=1);

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

class ContractTemplate
{
    public static function create(array $data): int
    {
        $pdo = getPDO();
        
        // Get current workspace company ID
        $companyId = null;
        $workspaceParam = $_GET['workspace'] ?? null;
        if ($workspaceParam) {
            $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
            $stmt->execute([$workspaceParam]);
            $company = $stmt->fetch();
            $companyId = $company['id'] ?? null;
        }
        
        // Fallback to tenant context
        if (!$companyId) {
            $companyId = TenantDB::getTenant();
        }
        
        if (!$companyId) {
            throw new Exception("No company context available for template creation");
        }
        
        $stmt = $pdo->prepare('INSERT INTO contract_templates (company_id, name, description, header_html, footer_html) VALUES (:company_id, :name, :description, :header_html, :footer_html)');
        $stmt->execute([
            ':company_id' => $companyId,
            ':name' => $data['name'],
            ':description' => $data['description'] ?? '',
            ':header_html' => $data['header_html'] ?? '',
            ':footer_html' => $data['footer_html'] ?? '',
        ]);
        return (int) $pdo->lastInsertId();
    }

    public static function find(int $id): ?array
    {
        $pdo = getPDO();
        $stmt = $pdo->prepare('SELECT * FROM contract_templates WHERE id = ?');
        $stmt->execute([$id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        return $row ?: null;
    }

    public static function all(): array
    {
        $pdo = getPDO();
        
        // Get current workspace company ID
        $companyId = null;
        $workspaceParam = $_GET['workspace'] ?? null;
        if ($workspaceParam) {
            $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
            $stmt->execute([$workspaceParam]);
            $company = $stmt->fetch();
            $companyId = $company['id'] ?? null;
        }
        
        // Fallback to tenant context
        if (!$companyId) {
            $companyId = TenantDB::getTenant();
        }
        
        if (!$companyId) {
            return [];
        }
        
        $stmt = $pdo->prepare('SELECT * FROM contract_templates WHERE company_id = ? ORDER BY name');
        $stmt->execute([$companyId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public static function update(int $id, array $data): void
    {
        $pdo = getPDO();
        $fields = [];
        $values = [':id' => $id];

        if (isset($data['name'])) {
            $fields[] = 'name = :name';
            $values[':name'] = $data['name'];
        }
        if (isset($data['description'])) {
            $fields[] = 'description = :description';
            $values[':description'] = $data['description'];
        }
        if (isset($data['header_html'])) {
            $fields[] = 'header_html = :header_html';
            $values[':header_html'] = $data['header_html'];
        }
        if (isset($data['footer_html'])) {
            $fields[] = 'footer_html = :footer_html';
            $values[':footer_html'] = $data['footer_html'];
        }

        // Use MySQL-compatible current timestamp
        $fields[] = 'updated_at = NOW()';

        if (!empty($fields)) {
            $sql = 'UPDATE contract_templates SET ' . implode(', ', $fields) . ' WHERE id = :id';
            $stmt = $pdo->prepare($sql);
            $stmt->execute($values);
        }
    }

    public static function delete(int $id): void
    {
        $pdo = getPDO();
        $stmt = $pdo->prepare('DELETE FROM contract_templates WHERE id = ?');
        $stmt->execute([$id]);
    }

    public static function attachModule(int $templateId, int $moduleId, int $sortOrder = 0): void
    {
        $pdo = getPDO();
        $stmt = $pdo->prepare('INSERT INTO contract_template_modules (contract_template_id, contract_module_id, sort_order, enabled) VALUES (:template_id, :module_id, :sort_order, 1) ON DUPLICATE KEY UPDATE sort_order = VALUES(sort_order), enabled = 1');
        $stmt->execute([
            ':template_id' => $templateId,
            ':module_id' => $moduleId,
            ':sort_order' => $sortOrder,
        ]);
    }

    public static function detachModule(int $templateId, int $moduleId): void
    {
        $pdo = getPDO();
        $stmt = $pdo->prepare('DELETE FROM contract_template_modules WHERE contract_template_id = :template_id AND contract_module_id = :module_id');
        $stmt->execute([
            ':template_id' => $templateId,
            ':module_id' => $moduleId,
        ]);
    }

    public static function getModules(int $templateId): array
    {
        $pdo = getPDO();
        
        // Get current workspace company ID
        $companyId = null;
        $workspaceParam = $_GET['workspace'] ?? null;
        if ($workspaceParam) {
            $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
            $stmt->execute([$workspaceParam]);
            $company = $stmt->fetch();
            $companyId = $company['id'] ?? null;
        }
        
        // Fallback to tenant context
        if (!$companyId) {
            $companyId = TenantDB::getTenant();
        }
        
        if (!$companyId) {
            return [];
        }
        
        $stmt = $pdo->prepare('
            SELECT cm.*, ctm.sort_order, ctm.enabled
            FROM contract_modules cm
            JOIN contract_template_modules ctm ON cm.id = ctm.contract_module_id
            WHERE ctm.contract_template_id = ? AND cm.company_id = ?
            ORDER BY ctm.sort_order, cm.name
        ');
        $stmt->execute([$templateId, $companyId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public static function getAvailableModules(int $templateId): array
    {
        $pdo = getPDO();
        
        // Get current workspace company ID
        $companyId = null;
        $workspaceParam = $_GET['workspace'] ?? null;
        if ($workspaceParam) {
            $stmt = $pdo->prepare("SELECT id FROM companies WHERE username = ?");
            $stmt->execute([$workspaceParam]);
            $company = $stmt->fetch();
            $companyId = $company['id'] ?? null;
        }
        
        // Fallback to tenant context
        if (!$companyId) {
            $companyId = TenantDB::getTenant();
        }
        
        if (!$companyId) {
            return [];
        }
        
        $stmt = $pdo->prepare('
            SELECT cm.* FROM contract_modules cm
            LEFT JOIN contract_template_modules ctm ON cm.id = ctm.contract_module_id AND ctm.contract_template_id = ?
            WHERE ctm.contract_module_id IS NULL AND cm.company_id = ?
            ORDER BY cm.category, cm.name, cm.price
        ');
        $stmt->execute([$templateId, $companyId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public static function updateModuleOrder(int $templateId, array $moduleIds): void
    {
        $pdo = getPDO();
        $pdo->beginTransaction();
        
        try {
            foreach ($moduleIds as $index => $moduleId) {
                $stmt = $pdo->prepare('UPDATE contract_template_modules SET sort_order = :sort_order WHERE contract_template_id = :template_id AND contract_module_id = :module_id');
                $stmt->execute([
                    ':sort_order' => $index,
                    ':template_id' => $templateId,
                    ':module_id' => $moduleId,
                ]);
            }
            $pdo->commit();
        } catch (Exception $e) {
            $pdo->rollback();
            throw $e;
        }
    }

    public static function setModuleEnabled(int $templateId, int $moduleId, bool $enabled): void
    {
        $pdo = getPDO();
        $stmt = $pdo->prepare(
            'UPDATE contract_template_modules SET enabled = :enabled WHERE contract_template_id = :template_id AND contract_module_id = :module_id'
        );
        $stmt->execute([
            ':enabled' => $enabled ? 1 : 0,
            ':template_id' => $templateId,
            ':module_id' => $moduleId,
        ]);
    }
}
