<?php

declare(strict_types=1);

function dental_privacy_processing_table(): string { return table('privacy_processing_activities'); }
function dental_privacy_requests_table(): string { return table('privacy_rights_requests'); }
function dental_privacy_incidents_table(): string { return table('privacy_incidents'); }
function dental_privacy_retention_table(): string { return table('privacy_retention_rules'); }

function dental_privacy_schema_ready(): bool
{
    return schema_table_exists(dental_privacy_processing_table())
        && schema_table_exists(dental_privacy_requests_table())
        && schema_table_exists(dental_privacy_incidents_table())
        && schema_table_exists(dental_privacy_retention_table())
        && function_exists('dental_audit_chain_schema_ready')
        && dental_audit_chain_schema_ready();
}

function dental_privacy_reference(string $prefix): string
{
    $prefix = strtoupper(preg_replace('/[^A-Z0-9]/i', '', $prefix) ?: 'PRV');
    try { $random = strtoupper(substr(bin2hex(random_bytes(5)), 0, 10)); }
    catch (Throwable) { $random = strtoupper(substr(hash('sha256', microtime(true) . '|' . getmypid()), 0, 10)); }
    return $prefix . '-' . date('Ymd') . '-' . $random;
}

function dental_privacy_branch_scope(): ?int
{
    if (superuser_primary_workspace()) return null;
    $branchId = signed_user_branch_id();
    return $branchId > 0 ? $branchId : 0;
}

function dental_privacy_branch_allowed(?int $branchId): bool
{
    if (superuser_primary_workspace()) return true;
    $userBranch = signed_user_branch_id();
    return $userBranch > 0 && $branchId !== null && $branchId === $userBranch;
}

function dental_privacy_clean_date(?string $value): ?string
{
    $value = trim((string)$value);
    if ($value === '') return null;
    $parsed = DateTimeImmutable::createFromFormat('Y-m-d', $value);
    return $parsed && $parsed->format('Y-m-d') === $value ? $value : null;
}

function dental_privacy_clean_datetime(?string $value): ?string
{
    $value = trim((string)$value);
    if ($value === '') return null;
    $timestamp = strtotime($value);
    return $timestamp === false ? null : date('Y-m-d H:i:s', $timestamp);
}

function dental_privacy_status_counts(): array
{
    if (!dental_privacy_schema_ready()) return ['requests_open'=>0,'incidents_open'=>0,'processing_active'=>0,'retention_active'=>0];
    $pdo = db();
    $scope = dental_privacy_branch_scope();
    $where = $scope === null ? '' : ' WHERE branch_id=' . (int)$scope;
    $requestWhere = $scope === null ? ' WHERE status NOT IN ("completed","rejected","withdrawn")' : ' WHERE branch_id=' . (int)$scope . ' AND status NOT IN ("completed","rejected","withdrawn")';
    $incidentWhere = $scope === null ? ' WHERE status NOT IN ("closed","false_positive")' : ' WHERE branch_id=' . (int)$scope . ' AND status NOT IN ("closed","false_positive")';
    return [
        'requests_open'=>(int)$pdo->query('SELECT COUNT(*) FROM `' . dental_privacy_requests_table() . '`' . $requestWhere)->fetchColumn(),
        'incidents_open'=>(int)$pdo->query('SELECT COUNT(*) FROM `' . dental_privacy_incidents_table() . '`' . $incidentWhere)->fetchColumn(),
        'processing_active'=>(int)$pdo->query('SELECT COUNT(*) FROM `' . dental_privacy_processing_table() . '`' . ($where === '' ? ' WHERE status="active"' : $where . ' AND status="active"'))->fetchColumn(),
        'retention_active'=>(int)$pdo->query('SELECT COUNT(*) FROM `' . dental_privacy_retention_table() . '`' . ($where === '' ? ' WHERE is_active=1' : $where . ' AND is_active=1'))->fetchColumn(),
    ];
}
