<?php

declare(strict_types=1);

namespace App\Models\Market;

use App\Models\Model;
use App\Models\User;

class Store extends Model
{
    protected ?string $table = 'str';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = [
        'hashkey',
        'storecode',
        'name',
        'description',
        'status',
        'created_by',
        'updated_by',
        'created_for',
        'remarks',
        'logs',
        'specs',
        'additionaldata',
        'owner_id',
        'manager_id',
        'category',
        'subcategory',
        'photourl',
        'address',
        'is_active',
        'store_type',
    ];

    protected array $casts = [
        'photourl' => 'array',
        'is_active' => 'boolean',
        'store_type'=> 'array',
        'specs' => 'array',
    ];

    /**
     * Relationships
     */
    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }

    public function updater()
    {
        return $this->belongsTo(User::class, 'updated_by');
    }

    public function createdFor()
    {
        return $this->belongsTo(User::class, 'created_for');
    }

    public function owner()
    {
        return $this->belongsTo(User::class, 'owner_id');
    }

    public function manager()
    {
        return $this->belongsTo(User::class, 'manager_id');
    }

    public function managers()
    {
        return $this->hasMany(StoreManager::class, 'store_id');
    }

    public function managerUsers()
    {
        return $this->belongsToMany(User::class, 'store_managers', 'store_id', 'user_id')
            ->withPivot(['hashkey', 'created_by', 'updated_by', 'is_active'])
            ->withTimestamps();
    }

    // public function products()
    // {
    //     return $this->hasMany(Product::class, 'store_id');
    // }

    public function products()
    {
        return $this->belongsToMany(Product::class, 'prd_str')
            ->withPivot(['available', 'price', 'is_active','sold','logs','reviews','status','remarks','description'])
            ->withTimestamps();
    }

    public function cooperatives()
    {
        return $this->belongsToMany(Organization::class, 'org_str', 'store_id', 'organization_id')
            ->where('organizations.type', 'COOPERATIVE')
            ->withTimestamps();
    }

    public function transactions()
    {
        return $this->hasMany(ProductTransaction::class, 'store_id');
    }

    public function transactionSessions()
    {
        return $this->hasMany(ProductTransactionSession::class, 'store_id');
    }


}
