<?php

namespace App\Models\Sales;

use App\Models\Branch;
use App\Models\Concerns\BelongsToTenant;
use App\Models\Concerns\BranchScoped;
use App\Models\Lookups\Status;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class PosSession extends Model
{
    // Deliberately not Auditable: the table has no created_by/updated_by
    // columns — the actor is tracked through opened_by/closed_by instead.
    use BelongsToTenant, BranchScoped, SoftDeletes;

    protected $fillable = [
        'branch_id', 'till_id', 'status_id',
        'opening_balance', 'opening_note', 'closing_balance',
        'expected_balance', 'variance', 'close_note',
        'opened_at', 'closed_at',
        'opened_by', 'closed_by',
    ];

    protected function casts(): array
    {
        return [
            'opening_balance' => 'decimal:2',
            'closing_balance' => 'decimal:2',
            'expected_balance' => 'decimal:2',
            'variance' => 'decimal:2',
            'opened_at' => 'datetime',
            'closed_at' => 'datetime',
        ];
    }

    public function invoices(): HasMany
    {
        return $this->hasMany(Invoice::class, 'pos_session_id');
    }

    public function branch(): BelongsTo
    {
        return $this->belongsTo(Branch::class, 'branch_id');
    }

    public function till(): BelongsTo
    {
        return $this->belongsTo(Till::class);
    }

    public function status(): BelongsTo
    {
        return $this->belongsTo(Status::class);
    }

    public function openedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'opened_by');
    }

    public function closedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'closed_by');
    }

    public function cashMovements(): HasMany
    {
        return $this->hasMany(CashMovement::class);
    }

    public function isOpen(): bool
    {
        return $this->status?->code === Status::SESSION_OPEN;
    }
}
