<?php

namespace App\Services;

use App\Models\Stall;
use App\Models\Merchant;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class StallService
{
    public function assignToMerchant(Stall $stall, Merchant $merchant): bool
    {
        if ($stall->is_occupied) {
            return false;
        }
        if (!$merchant->isApproved()) {
            return false;
        }
        return DB::transaction(function () use ($stall, $merchant) {
            $stall->merchant_id = $merchant->id;
            $stall->is_occupied = true;
            $stall->save();
            return true;
        });
    }

    public function release(Stall $stall): bool
    {
        if (!$stall->is_occupied) {
            return false;
        }
        return DB::transaction(function () use ($stall) {
            $stall->merchant_id = null;
            $stall->is_occupied = false;
            $stall->save();
            return true;
        });
    }

    public function getAvailable(): Collection
    {
        return Stall::where('is_occupied', false)->get();
    }

    public function getOccupied(): Collection
    {
        return Stall::where('is_occupied', true)->get();
    }
}
