<?php

declare(strict_types=1);

namespace App\Services;

use InvalidArgumentException;
use PDO;

final class CompanyProfileService
{
    public function __construct(private PDO $pdo)
    {
    }

    public function tableReady(): bool
    {
        return table_exists($this->pdo, 'company_profile');
    }

    public function profile(): array
    {
        return $this->pdo->query("SELECT * FROM company_profile WHERE id=1 LIMIT 1")->fetch(PDO::FETCH_ASSOC) ?: [];
    }

    public function save(array $input, array $files, array $current): void
    {
        $logoPath = (string)($current['logo_path'] ?? '');
        if (!empty($files['logo']['name'] ?? '')) {
            $logoPath = $this->uploadLogo($files['logo']);
        }

        $st = $this->pdo->prepare("INSERT INTO company_profile (id, name, subtitle, address, phone, email, website, tax_no, logo_path)
            VALUES (1,?,?,?,?,?,?,?,?)
            ON DUPLICATE KEY UPDATE name=VALUES(name), subtitle=VALUES(subtitle), address=VALUES(address), phone=VALUES(phone), email=VALUES(email), website=VALUES(website), tax_no=VALUES(tax_no), logo_path=VALUES(logo_path)");
        $st->execute([
            trim((string)($input['name'] ?? '')),
            trim((string)($input['subtitle'] ?? '')),
            trim((string)($input['address'] ?? '')),
            trim((string)($input['phone'] ?? '')),
            trim((string)($input['email'] ?? '')),
            trim((string)($input['website'] ?? '')),
            trim((string)($input['tax_no'] ?? '')),
            $logoPath,
        ]);
    }

    private function uploadLogo(array $file): string
    {
        $err = (int)($file['error'] ?? UPLOAD_ERR_NO_FILE);
        if ($err !== UPLOAD_ERR_OK) {
            throw new InvalidArgumentException('حدث خطأ أثناء رفع اللوجو.');
        }

        $tmp = (string)($file['tmp_name'] ?? '');
        if ($tmp === '' || !is_uploaded_file($tmp)) {
            throw new InvalidArgumentException('ملف اللوجو غير صالح.');
        }

        $size = (int)($file['size'] ?? 0);
        if ($size <= 0 || $size > 2 * 1024 * 1024) {
            throw new InvalidArgumentException('حجم اللوجو يجب ألا يتجاوز 2MB.');
        }

        $finfo = new \finfo(FILEINFO_MIME_TYPE);
        $mime = (string)$finfo->file($tmp);
        $allowed = [
            'image/png' => 'png',
            'image/jpeg' => 'jpg',
            'image/webp' => 'webp',
        ];
        if (!isset($allowed[$mime])) {
            throw new InvalidArgumentException('صيغة اللوجو غير مدعومة. استخدم PNG/JPG/WEBP');
        }

        if (@getimagesize($tmp) === false) {
            throw new InvalidArgumentException('ملف الصورة غير صالح.');
        }

        $uploadDir = APP_BASE_PATH . '/public/uploads';
        if (!is_dir($uploadDir) && !@mkdir($uploadDir, 0755, true) && !is_dir($uploadDir)) {
            throw new InvalidArgumentException('تعذر إنشاء مجلد public/uploads');
        }

        $fname = 'company_logo_' . bin2hex(random_bytes(8)) . '.' . $allowed[$mime];
        $dest = $uploadDir . '/' . $fname;
        if (!@move_uploaded_file($tmp, $dest)) {
            throw new InvalidArgumentException('لم يتم رفع اللوجو. تحقق من صلاحيات مجلد public/uploads');
        }

        return 'uploads/' . $fname;
    }
}
