<?php

declare(strict_types=1);

namespace App\Shared\Support;

use App\Shared\Schema\SchemaSupport;
use PDO;
use Throwable;

final class CompanySupport
{
    public static function profile(PDO $pdo): array
    {
        $defaults = [
            'name' => (string) ((AppConfigSupport::read('app.name', '') ?: 'اسم الشركة')),
            'subtitle' => 'العنوان - الهاتف - البريد',
            'address' => '',
            'phone' => '',
            'email' => '',
            'website' => '',
            'tax_no' => '',
            'logo_path' => '',
        ];

        if (!SchemaSupport::tableExists($pdo, 'company_profile')) {
            return $defaults;
        }

        try {
            $st = $pdo->query("SELECT * FROM company_profile WHERE id = 1 LIMIT 1");
            $row = $st ? $st->fetch(PDO::FETCH_ASSOC) : false;
            if (!$row) {
                return $defaults;
            }

            $name = trim((string) ($row['name'] ?? ''));
            $subtitle = trim((string) ($row['subtitle'] ?? ''));
            if ($subtitle === '') {
                $parts = [];
                $address = trim((string) ($row['address'] ?? ''));
                $phone = trim((string) ($row['phone'] ?? ''));
                $email = trim((string) ($row['email'] ?? ''));
                if ($address !== '') {
                    $parts[] = $address;
                }
                if ($phone !== '') {
                    $parts[] = $phone;
                }
                if ($email !== '') {
                    $parts[] = $email;
                }
                $subtitle = !empty($parts) ? implode(' - ', $parts) : $defaults['subtitle'];
            }

            return [
                'name' => $name !== '' ? $name : $defaults['name'],
                'subtitle' => $subtitle,
                'address' => (string) ($row['address'] ?? ''),
                'phone' => (string) ($row['phone'] ?? ''),
                'email' => (string) ($row['email'] ?? ''),
                'website' => (string) ($row['website'] ?? ''),
                'tax_no' => (string) ($row['tax_no'] ?? ''),
                'logo_path' => (string) ($row['logo_path'] ?? ''),
            ];
        } catch (Throwable $e) {
            return $defaults;
        }
    }
}
