<?php

declare(strict_types=1);

namespace App\Observers;

use App\Models\Job;
use App\Models\Owner;
use App\Models\OwnerLedgerEntry;
use App\Models\Vehicle;

class JobObserver
{
    public function saved(Job $job): void
    {
        // Look up vehicle + owner without brand/global scopes
        $vehicle = $job->vehicle_id
            ? Vehicle::withoutGlobalScopes()->find($job->vehicle_id)
            : null;

        $owner = $vehicle && $vehicle->owner_id
            ? Owner::withoutGlobalScopes()->find($vehicle->owner_id)
            : null;

        $gross = (int) ($job->charge_amount_cents ?? 0);

        // If no owner or no gross, delete any existing earning and bail
        if (! $owner || $gross <= 0) {
            OwnerLedgerEntry::where('job_id', $job->id)
                ->where('type', 'earning')
                ->delete();

            return;
        }

        // OWNER SPLIT:
        // Use vehicle->owner_share_percent if set, otherwise default to 70%
        $sharePercent = $vehicle->owner_share_percent ?? 70;
        $sharePercent = max(0, min(100, (int) $sharePercent));

        $amount = (int) floor($gross * $sharePercent / 100);

        if ($amount <= 0) {
            OwnerLedgerEntry::where('job_id', $job->id)
                ->where('type', 'earning')
                ->delete();

            return;
        }

        $occurredAt = $job->end_at
            ?? $job->start_at
            ?? $job->created_at
            ?? now();

        OwnerLedgerEntry::updateOrCreate(
            [
                'owner_id' => $owner->id,
                'job_id'   => $job->id,
                'type'     => 'earning',
            ],
            [
                'brand_id'     => $owner->brand_id ?? null,
                'vehicle_id'   => $vehicle->id,
                'amount_cents' => $amount,
                'occurred_at'  => $occurredAt,
                'description'  => $job->booking_reference ?: 'Hire revenue',
            ],
        );
    }

    public function deleted(Job $job): void
    {
        OwnerLedgerEntry::where('job_id', $job->id)
            ->where('type', 'earning')
            ->delete();
    }
}
