<?php

namespace Modules\PortalApi\Entities;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;

class PortalBrand extends Model
{
    protected $table = 'portal_brands';

    protected $fillable = [
        'business_id', 'slug', 'custom_domain',
        'name', 'accent_hex', 'logo_url',
        'contact_phone', 'contact_email', 'address',
        'login_methods', 'is_active', 'public_booking', 'booking_otp',
    ];

    protected $casts = [
        'login_methods'  => 'array',
        'is_active'      => 'boolean',
        'public_booking' => 'boolean',
        'booking_otp'    => 'boolean',
    ];

    /* ─── Resolvers ─────────────────────────────────────────── */

    /**
     * Master brand resolver. Priority:
     *   1. Custom domain — clinic CNAME'd their own domain
     *   2. Subdomain that matches a slug — clinic1.staticerp.com → slug=clinic1
     *   3. Path slug — staticerp.com/app/clinic1/... → slug=clinic1
     *   4. Default — first active brand, OR null
     */
    public static function forRequest(Request $request): ?self
    {
        $host = strtolower(explode(':', $request->getHost())[0]);

        // 1. Exact custom-domain match
        if ($brand = self::activeWhere('custom_domain', $host)) {
            return $brand;
        }

        // 2. Subdomain — first label of host. Ignore single-label hosts
        // (e.g. 'localhost') and 'www'.
        $parts = explode('.', $host);
        if (count($parts) >= 3 && $parts[0] !== 'www') {
            if ($brand = self::activeWhere('slug', $parts[0])) {
                return $brand;
            }
        }

        // 3. Path slug — /app/{slug}/...
        $segs  = explode('/', trim($request->path(), '/'));
        $appIx = array_search('app', $segs, true);
        if ($appIx !== false && isset($segs[$appIx + 1])) {
            $candidate = strtolower($segs[$appIx + 1]);
            $reserved = ['login','home','pets','book','appointments','card','me','auth'];
            if (! in_array($candidate, $reserved, true)) {
                if ($brand = self::activeWhere('slug', $candidate)) {
                    return $brand;
                }
            }
        }

        // 4. Default — let the API endpoint render a fallback brand if null
        return self::where('is_active', true)->orderBy('id')->first();
    }

    public static function forSlug(string $slug): ?self
    {
        return self::activeWhere('slug', $slug);
    }

    private static function activeWhere(string $col, string $val): ?self
    {
        return self::where($col, $val)->where('is_active', true)->first();
    }

    /* ─── Serializer ────────────────────────────────────────── */

    /**
     * The shape the PWA expects from /api/v1/portal/brand/{slug}.
     * Keep this stable — it's the contract between PortalApi and pwa-owner/.
     */
    public function toPwaPayload(): array
    {
        return [
            'slug'           => $this->slug,
            'name'           => $this->name,
            'logo_url'       => $this->logo_url,
            'accent_hex'     => $this->accent_hex ?: '#0d9488',
            'contact_phone'  => $this->contact_phone,
            'contact_email'  => $this->contact_email,
            'address'        => $this->address,
            'login_methods'  => $this->login_methods ?: ['otp','magic','password','staff'],
        ];
    }
}
