<?php

require_once __DIR__ . '/SystemSettings.php';

class Branding {
    private static $settings = null;

    public static function settings() {
        if (self::$settings === null) {
            self::$settings = (new SystemSettings())->all();
        }

        return self::$settings;
    }

    public static function companyName() {
        $settings = self::settings();
        return $settings['company_name'] ?? 'Company Name';
    }

    public static function companyNameUpper() {
        return strtoupper(self::companyName());
    }

    public static function logoUrl() {
        $settings = self::settings();
        return $settings['company_logo'] ?? '/IMS/assets/images/settings/company-logo.png';
    }

    public static function logoFilePath() {
        return self::filePathForLogo(self::logoUrl());
    }

    public static function filePathForLogo($logo) {
        $logo = trim((string)$logo);
        if ($logo === '') {
            return '';
        }

        if (preg_match('/^https?:\/\//i', $logo)) {
            return $logo;
        }

        $projectRoot = dirname(__DIR__);
        $imsPrefix = '/IMS/';
        if (strpos($logo, $imsPrefix) === 0) {
            return $projectRoot . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, substr($logo, strlen($imsPrefix)));
        }

        return $projectRoot . DIRECTORY_SEPARATOR . ltrim(str_replace('/', DIRECTORY_SEPARATOR, $logo), DIRECTORY_SEPARATOR);
    }

    public static function branchLogoUrl($branch) {
        $branch = is_array($branch) ? $branch : [];
        $branchLogo = trim((string)($branch['branch_logo'] ?? ''));
        if ($branchLogo === '') {
            return self::logoUrl();
        }

        // Remote logos cannot be checked locally. For an app-hosted logo, avoid
        // returning a stale database path after its upload has been removed.
        if (preg_match('/^https?:\/\//i', $branchLogo)) {
            return $branchLogo;
        }

        $branchLogoFile = self::filePathForLogo($branchLogo);
        if ($branchLogoFile === '' || !is_file($branchLogoFile)) {
            return self::logoUrl();
        }

        $publicLogo = str_replace('\\', '/', $branchLogo);
        if (str_starts_with($publicLogo, '/')) {
            return $publicLogo;
        }

        $appBase = defined('BASE_URL') ? trim((string)BASE_URL, '/') : 'IMS';
        return '/' . ($appBase !== '' ? $appBase . '/' : '') . ltrim($publicLogo, '/');
    }

    public static function branchLogoFilePath($branch) {
        return self::filePathForLogo(self::branchLogoUrl($branch));
    }

    public static function branchCompanyName($branch) {
        $branch = is_array($branch) ? $branch : [];
        $branchCompanyName = trim((string)($branch['branch_company_name'] ?? ''));
        return $branchCompanyName !== '' ? $branchCompanyName : self::companyName();
    }

    public static function pageTitle($title) {
        return trim($title) . ' - ' . self::companyName();
    }

    public static function companyDetails(array $overrides = []) {
        return array_merge([
            'name' => self::companyName(),
            'logo' => self::logoUrl(),
            'logo_file' => self::logoFilePath(),
            'address' => '',
            'phone' => '',
            'email' => '',
            'website' => '',
            'tagline' => self::settings()['service_body'] ?? '',
        ], $overrides);
    }

    public static function documentDetailsForBranch($branch, array $overrides = []) {
        $branch = is_array($branch) ? $branch : [];

        return self::companyDetails(array_merge([
            'name' => self::branchCompanyName($branch),
            'logo' => self::branchLogoUrl($branch),
            'logo_file' => self::branchLogoFilePath($branch),
            'address' => $branch['branch_address'] ?? '',
            'phone' => $branch['branch_phone'] ?? '',
            'email' => $branch['branch_email'] ?? '',
            'website' => $branch['branch_website'] ?? '',
        ], $overrides));
    }

    public static function documentDetailsForBranchId(PDO $conn, $branchId, array $overrides = []) {
        $branchId = (int)$branchId;
        if ($branchId <= 0) {
            return self::companyDetails($overrides);
        }

        $stmt = $conn->prepare('SELECT * FROM branches WHERE branch_id = :branch_id LIMIT 1');
        $stmt->execute([':branch_id' => $branchId]);
        return self::documentDetailsForBranch($stmt->fetch(PDO::FETCH_ASSOC) ?: [], $overrides);
    }

    public static function contactLine(array $details, $separator = ' | ') {
        $parts = [];
        if (!empty($details['phone'])) {
            $parts[] = 'Phone: ' . $details['phone'];
        }
        if (!empty($details['email'])) {
            $parts[] = 'Email: ' . $details['email'];
        }
        if (!empty($details['website'])) {
            $parts[] = 'Web: ' . $details['website'];
        }

        return implode($separator, $parts);
    }
}
