<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\DB;

class SameBranchAs implements ValidationRule
{
    public function __construct(
        private string $table,
        private int $branchId,
        private string $message = 'The selected record must belong to the same branch.',
    ) {}

    public function validate(string $attribute, mixed $value, Closure $fail): void
    {
        if (! is_numeric($value)) {
            return;
        }

        $belongsToBranch = DB::table($this->table)
            ->where('id', (int) $value)
            ->where('branch_id', $this->branchId)
            ->exists();

        if (! $belongsToBranch) {
            $fail($this->message);
        }
    }
}
