<?php

declare(strict_types=1);

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

class Module
{
    public static function all(): array
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('SELECT * FROM modules WHERE company_id = ? ORDER BY created_at DESC');
        $stmt->execute([$companyId]);

        return $stmt->fetchAll();
    }

    public static function find(int $id): ?array
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('SELECT * FROM modules WHERE id = :id AND company_id = :company_id');
        $stmt->execute([':id' => $id, ':company_id' => $companyId]);
        $module = $stmt->fetch();

        return $module ?: null;
    }

    public static function create(array $data): int
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        
        if ($companyId === null) {
            throw new RuntimeException('Company ID not available. Workspace context not properly initialized.');
        }
        
        $stmt = $pdo->prepare('INSERT INTO modules (title, content_html, default_required, company_id, created_at) VALUES (:title, :content_html, :default_required, :company_id, :created_at)');
        $stmt->execute([
            ':title' => $data['title'],
            ':content_html' => $data['content_html'] ?? null,
            ':default_required' => $data['default_required'] ?? 0,
            ':company_id' => $companyId,
            ':created_at' => date('c'),
        ]);

        return (int) $pdo->lastInsertId();
    }

    public static function update(int $id, array $data): void
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('UPDATE modules SET title = :title, content_html = :content_html, default_required = :default_required WHERE id = :id AND company_id = :company_id');
        $stmt->execute([
            ':id' => $id,
            ':title' => $data['title'],
            ':content_html' => $data['content_html'] ?? null,
            ':default_required' => $data['default_required'] ?? 0,
            ':company_id' => $companyId,
        ]);
    }

    public static function delete(int $id): void
    {
        $pdo = getPDO();
        $companyId = TenantDB::getTenant();
        $stmt = $pdo->prepare('DELETE FROM modules WHERE id = :id AND company_id = :company_id');
        $stmt->execute([':id' => $id, ':company_id' => $companyId]);
    }
}
