<?php

namespace App\Models;

class Setting extends BaseModel
{
    public function get(): array
    {
        $stmt = $this->pdo->query('SELECT * FROM company_settings ORDER BY id ASC LIMIT 1');
        $setting = $stmt->fetch() ?: [];
        if (!empty($setting['locations'])) {
            $setting['locations'] = array_filter(array_map('trim', explode(',', $setting['locations'])));
        } else {
            $setting['locations'] = [];
        }
        return $setting;
    }

    public function update(array $data): void
    {
        $existing = $this->get();

        if ($existing) {
            $stmt = $this->pdo->prepare('UPDATE company_settings SET company_name = :company_name, tagline = :tagline,
                email = :email, phone = :phone, address = :address, locations = :locations, logo_path = :logo_path, updated_at = NOW() WHERE id = :id');
            $stmt->execute([
                'company_name' => $data['company_name'],
                'tagline' => $data['tagline'],
                'email' => $data['email'],
                'phone' => $data['phone'],
                'address' => $data['address'],
                'locations' => !empty($data['locations']) ? implode(',', array_map('trim', $data['locations'])) : null,
                'logo_path' => $data['logo_path'],
                'id' => $existing['id'],
            ]);
        } else {
            $stmt = $this->pdo->prepare('INSERT INTO company_settings (company_name, tagline, email, phone, address, locations, logo_path)
                VALUES (:company_name, :tagline, :email, :phone, :address, :locations, :logo_path)');
            $stmt->execute([
                'company_name' => $data['company_name'],
                'tagline' => $data['tagline'],
                'email' => $data['email'],
                'phone' => $data['phone'],
                'address' => $data['address'],
                'locations' => !empty($data['locations']) ? implode(',', array_map('trim', $data['locations'])) : null,
                'logo_path' => $data['logo_path'],
            ]);
        }
    }
}

