<?php

declare(strict_types=1);

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

class ContractModule
{
    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 module creation");
        }
        
        $stmt = $pdo->prepare('INSERT INTO contract_modules (company_id, name, description, price, category, is_active) VALUES (:company_id, :name, :description, :price, :category, :is_active)');
        $stmt->execute([
            ':company_id' => $companyId,
            ':name' => $data['title'] ?? $data['name'] ?? '',  // Handle both 'title' and 'name'
            ':description' => $data['content_html'] ?? $data['description'] ?? '',  // Handle both 'content_html' and 'description'
            ':price' => $data['price'] ?? 0.00,
            ':category' => $data['category'] ?? 'general',
            ':is_active' => $data['is_active'] ?? 1,
        ]);
        return (int) $pdo->lastInsertId();
    }

    public static function find(int $id): ?array
    {
        $pdo = getPDO();
        $stmt = $pdo->prepare('SELECT * FROM contract_modules 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_modules WHERE company_id = ? ORDER BY category, name, price');
        $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['title'])) {
            $fields[] = 'name = :title';
            $values[':title'] = $data['title'];
        }
        if (isset($data['content_html'])) {
            $fields[] = 'description = :content_html';
            $values[':content_html'] = $data['content_html'];
        }
        if (isset($data['category'])) {
            $fields[] = 'category = :category';
            $values[':category'] = $data['category'];
        }
        if (isset($data['price'])) {
            $fields[] = 'price = :price';
            $values[':price'] = $data['price'];
        }
        if (isset($data['default_required'])) {
            $fields[] = 'is_active = :default_required';
            $values[':default_required'] = $data['default_required'];
        }

        $fields[] = 'updated_at = NOW()';

        if (!empty($fields)) {
            $sql = 'UPDATE contract_modules 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_modules WHERE id = ?');
        $stmt->execute([$id]);
    }

    public static function getByCategory(string $category): array
    {
        $pdo = getPDO();
        $stmt = $pdo->prepare('SELECT * FROM contract_modules WHERE category = ? ORDER BY sort_order, title');
        $stmt->execute([$category]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    public static function getCategories(): array
    {
        $pdo = getPDO();
        $stmt = $pdo->query('SELECT DISTINCT category FROM contract_modules ORDER BY category');
        return $stmt->fetchAll(PDO::FETCH_COLUMN);
    }
}
