<?php
declare(strict_types=1);

namespace App\Models;

use App\Core\Model;
use App\Models\AuditLogModel;
use PDO;

/**
 * Tenant Model for business profile and settings
 */
class TenantModel extends Model
{
    protected string $table = 'tenants';
    private AuditLogModel $auditLogger;

    public function __construct()
    {
        parent::__construct();
        $this->auditLogger = new AuditLogModel();
    }

    public function updateProfile(int $tenantId, int $userId, array $data): bool
    {
        $old = $this->find($tenantId);
        $result = $this->update($tenantId, $data);
        if ($result) {
            $this->auditLogger->log($tenantId, $userId, 'update', 'business_profile', $tenantId, $old, $data);
        }
        return $result;
    }

    public function getSettings(int $tenantId): array
    {
        $stmt = $this->db->prepare("SELECT * FROM tenant_settings WHERE tenant_id = ?");
        $stmt->execute([$tenantId]);
        $settings = $stmt->fetch();

        if (!$settings) {
            // Initialize default settings if none exist
            $this->db->prepare("INSERT INTO tenant_settings (tenant_id) VALUES (?)")->execute([$tenantId]);
            return $this->getSettings($tenantId);
        }

        return $settings;
    }

    public function updateSettings(int $tenantId, int $userId, array $data): bool
    {
        $old = $this->getSettings($tenantId);

        $fields = array_map(fn($f) => "$f = :$f", array_keys($data));
        $sql = "UPDATE tenant_settings SET " . implode(', ', $fields) . " WHERE tenant_id = :tenant_id";

        $data['tenant_id'] = $tenantId;
        $stmt = $this->db->prepare($sql);
        $result = $stmt->execute($data);

        if ($result) {
            $this->auditLogger->log($tenantId, $userId, 'update', 'tenant_settings', $tenantId, $old, $data);
        }
        return $result;
    }

    public function updateLogo(int $tenantId, int $userId, string $logoPath): bool
    {
        $old = $this->find($tenantId);
        $result = $this->update($tenantId, ['logo' => $logoPath]);
        if ($result) {
            $this->auditLogger->log($tenantId, $userId, 'update', 'business_logo', $tenantId, ['logo' => $old['logo']], ['logo' => $logoPath]);
        }
        return $result;
    }
}
