<?php

namespace App\Models;

use App\Models\Concerns\BelongsToCompany;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Storage;

/**
 * Per company, not per platform: each company connects its own gateway
 * credentials so its students' payments land in that company's own
 * PayPal/Stripe/etc. account, not ABIC_E-Learning's. One row per gateway
 * name PER COMPANY — CompanyController seeds the five blank ones a new
 * company starts with; PaymentGatewaySeeder does the same for the root
 * company at install time.
 */
class PaymentGateway extends Model
{
    use HasFactory, BelongsToCompany;

    // Deliberately no cast on `config`. Every read (PaymentService,
    // PaymentGatewayController) and every write (here, the seeder, the
    // controller's update()) already does its own json_encode()/
    // json_decode() by hand — an 'array' cast on top of that silently
    // encoded the already-encoded string a second time on write, and
    // unwrapped only one of the two layers on read, leaving `->config` as
    // a string no matter what. It happened to still work, purely because
    // every caller's own manual decode undid the one remaining layer —
    // but it's a trap for the next person who trusts the cast and reads
    // `->config` directly expecting an array. Removing it makes what's
    // stored match what's written: one json_encode(), decoded once.
    protected $guarded = ['id'];

    public function image(): BelongsTo
    {
        return $this->belongsTo(Media::class, 'media_id');
    }

    public function imagePath(): Attribute
    {
        $image = asset('media/dummy-image.jpg');

        if ($this->image && file_exists(public_path($this->image->src))) {
            $image = asset($this->image->src);
        }

        return Attribute::make(
            get: fn () => $image,
        );
    }
}
