<?php
declare(strict_types=1);

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

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

if (file_exists(__DIR__ . '/../inc/app_url.php')) {
    require_once __DIR__ . '/../inc/app_url.php';
}

if (file_exists(__DIR__ . '/../inc/auth.php')) {
    require_once __DIR__ . '/../inc/auth.php';
}

if (!function_exists('financial_require_access')) {
    function financial_require_access(): void
    {
        if (function_exists('require_login')) {
            require_login();
        } elseif (empty($_SESSION['user_id'])) {
            header('Location: /HLG-Justice-Hub/index.html?e=1');
            exit;
        }

        $role = strtoupper(trim((string)($_SESSION['role'] ?? 'STAFF')));
        if (!in_array($role, ['OWNER', 'ADMIN', 'SUPER_ADMIN'], true)) {
            http_response_code(403);
            exit('غير مصرح');
        }
    }
}

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

if (!function_exists('financial_u')) {
    function financial_u(string $path): string
    {
        $path = 'financial/' . ltrim($path, '/');

        if (function_exists('app_url')) {
            return app_url($path);
        }

        return '/HLG-Justice-Hub/' . $path;
    }
}

if (!function_exists('financial_db')) {
    function financial_db(): PDO
    {
        $pdo = db();
        if (!$pdo instanceof PDO) {
            http_response_code(500);
            exit('DB not ready');
        }

        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
        return $pdo;
    }
}

if (!function_exists('financial_branch_id')) {
    function financial_branch_id(): int
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }

        if (isset($_GET['branch_id'])) {
            $selectedBranchId = (int)$_GET['branch_id'];
            if (in_array($selectedBranchId, [1, 2], true)) {
                $_SESSION['financial_branch_id'] = $selectedBranchId;
                $_SESSION['branch_id'] = $selectedBranchId;
            }
        }

        $branchId = (int)($_SESSION['financial_branch_id'] ?? $_SESSION['branch_id'] ?? 1);
        return in_array($branchId, [1, 2], true) ? $branchId : 1;
    }
}

if (!function_exists('financial_user_id')) {
    function financial_user_id(): int
    {
        return (int)($_SESSION['user_id'] ?? 0);
    }
}

if (!function_exists('financial_table_columns')) {
    function financial_table_columns(PDO $pdo, string $table): array
    {
        static $cache = [];
        if (isset($cache[$table])) {
            return $cache[$table];
        }

        $cols = [];
        try {
            $st = $pdo->query('SHOW COLUMNS FROM `' . str_replace('`', '', $table) . '`');
            foreach ($st->fetchAll(PDO::FETCH_ASSOC) as $col) {
                $cols[] = (string)$col['Field'];
            }
        } catch (Throwable $e) {
            $cols = [];
        }

        return $cache[$table] = $cols;
    }
}

if (!function_exists('financial_has_column')) {
    function financial_has_column(PDO $pdo, string $table, string $column): bool
    {
        return in_array($column, financial_table_columns($pdo, $table), true);
    }
}

if (!function_exists('financial_upload_attachment')) {
    function financial_upload_attachment(string $fieldName, string $prefix): ?string
    {
        if (empty($_FILES[$fieldName]['name']) || !is_uploaded_file((string)$_FILES[$fieldName]['tmp_name'])) {
            return null;
        }

        $allowedExt = ['pdf', 'jpg', 'jpeg', 'png', 'webp'];
        $allowedMime = [
            'application/pdf',
            'image/jpeg',
            'image/png',
            'image/webp',
        ];
        $maxSize = 5 * 1024 * 1024;

        $fileName = (string)$_FILES[$fieldName]['name'];
        $fileSize = (int)$_FILES[$fieldName]['size'];
        $tmpName  = (string)$_FILES[$fieldName]['tmp_name'];
        $ext      = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));

        if (!in_array($ext, $allowedExt, true)) {
            throw new RuntimeException('نوع الملف غير مسموح');
        }

        if ($fileSize <= 0 || $fileSize > $maxSize) {
            throw new RuntimeException('حجم الملف أكبر من 5MB أو غير صحيح');
        }

        $mime = '';
        if (function_exists('finfo_open')) {
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            if ($finfo) {
                $mime = (string)finfo_file($finfo, $tmpName);
                finfo_close($finfo);
            }
        }

        if ($mime !== '' && !in_array($mime, $allowedMime, true)) {
            throw new RuntimeException('نوع الملف غير مسموح');
        }

        $uploadDir = __DIR__ . '/uploads/financial/';
        if (!is_dir($uploadDir) && !mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) {
            throw new RuntimeException('تعذر إنشاء مجلد المرفقات');
        }

        $safePrefix = preg_replace('/[^a-zA-Z0-9_\-]/', '', $prefix) ?: 'file';
        $newName = $safePrefix . '_' . date('YmdHis') . '_' . bin2hex(random_bytes(5)) . '.' . $ext;

        if (!move_uploaded_file($tmpName, $uploadDir . $newName)) {
            throw new RuntimeException('فشل رفع الملف');
        }

        return 'uploads/financial/' . $newName;
    }
}

if (!function_exists('financial_delete_attachment_file')) {
    function financial_delete_attachment_file(?string $path): void
    {
        $path = trim((string)$path);
        if ($path === '' || str_contains($path, '..')) {
            return;
        }

        $full = __DIR__ . '/' . ltrim($path, '/');
        $base = realpath(__DIR__ . '/uploads/financial');
        $real = realpath($full);

        if ($base && $real && str_starts_with($real, $base) && is_file($real)) {
            @unlink($real);
        }
    }
}
