<?php
declare(strict_types=1);

if (!function_exists('h')) {
    function h($value): string {
        return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
    }
}

function require_login(): void {
    if (empty($_SESSION['user_id'])) {
        header('Location: login.php');
        exit;
    }
}

function require_admin(): void {
    require_login();
    if (($_SESSION['role'] ?? 'brother') !== 'admin') {
        header('Location: dashboard.php');
        exit;
    }
}

function app_setting(PDO $pdo, string $key, string $default = ''): string {
    try {
        $stmt = $pdo->prepare("SELECT setting_value FROM app_settings WHERE setting_key = ? LIMIT 1");
        $stmt->execute([$key]);
        $value = $stmt->fetchColumn();
        return ($value !== false && $value !== null) ? (string)$value : $default;
    } catch (Throwable $e) {
        return $default;
    }
}

function save_app_setting(PDO $pdo, string $key, string $value): void {
    $stmt = $pdo->prepare("INSERT INTO app_settings (setting_key, setting_value) VALUES (?, ?) ON DUPLICATE KEY UPDATE setting_value = VALUES(setting_value)");
    $stmt->execute([$key, $value]);
}

function normalize_identifier(string $value): string {
    return strtoupper(trim($value));
}

function split_identifiers(?string $value): array {
    $value = strtoupper(trim((string)$value));
    if ($value === '') return [];
    $value = str_replace([' ', ',', '/', '|'], ['', '&', '&', '&'], $value);
    return array_values(array_filter(array_map('trim', explode('&', $value))));
}

function phone_digits(string $phone): string {
    return preg_replace('/\D+/', '', $phone);
}

function current_rotation_month(): string {
    return date('F');
}

function get_brother_by_identifier(PDO $pdo, string $identifier): ?array {
    $stmt = $pdo->prepare("SELECT * FROM brothers WHERE identifier = ? LIMIT 1");
    $stmt->execute([normalize_identifier($identifier)]);
    $row = $stmt->fetch();
    return $row ?: null;
}

function resolve_assignment_names(PDO $pdo, string $assignment): array {
    $result = [];
    foreach (split_identifiers($assignment) as $identifier) {
        $brother = get_brother_by_identifier($pdo, $identifier);
        $result[] = [
            'identifier' => $identifier,
            'name' => $brother['name'] ?? $identifier,
            'phone' => $brother['phone'] ?? '',
        ];
    }
    return $result;
}

function is_video_file(string $url): bool {
    return preg_match('/\.(mp4|webm|ogg|mov)(\?.*)?$/i', $url) === 1;
}

function is_audio_file(string $url): bool {
    return preg_match('/\.(mp3|wav|ogg|m4a)(\?.*)?$/i', $url) === 1;
}

function is_pdf_file(string $url): bool {
    return preg_match('/\.pdf(\?.*)?$/i', $url) === 1;
}

function youtube_embed_url(string $url): string {
    $url = trim($url);
    if (strpos($url, 'youtu.be/') !== false) {
        $parts = explode('youtu.be/', $url);
        $id = explode('?', $parts[1] ?? '')[0];
        return $id ? 'https://www.youtube.com/embed/' . $id : '';
    }
    if (strpos($url, 'youtube.com') !== false) {
        parse_str(parse_url($url, PHP_URL_QUERY) ?? '', $query);
        if (!empty($query['v'])) return 'https://www.youtube.com/embed/' . $query['v'];
    }
    return '';
}

function table_has_column(PDO $pdo, string $table, string $column): bool {
    $stmt = $pdo->prepare("SHOW COLUMNS FROM `$table` LIKE ?");
    $stmt->execute([$column]);
    return (bool)$stmt->fetchColumn();
}

function add_column_if_missing(PDO $pdo, string $table, string $column, string $definition): void {
    if (!table_has_column($pdo, $table, $column)) {
        $pdo->exec("ALTER TABLE `$table` ADD COLUMN `$column` $definition");
    }
}
