<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class OdooSystem extends Model
{
    protected $table = 'odoo_systems';
    protected $fillable = [
        'name', 
        'slug', 
        'description', 
        'is_active',
        'partner_table',
        'partner_filter_conditions'
    ];

    protected $casts = [
        'partner_filter_conditions' => 'array',
    ];

    public function sections()
    {
        return $this->hasMany(OdooJvSection::class, 'system_id')->orderBy('sort_order');
    }

    /**
     * Get all partners for this system (both main and sub-partners)
     * 
     * @return \Illuminate\Support\Collection
     */
    public function getPartners()
    {
        if (!$this->partner_table) {
            return collect();
        }

        $tableName = $this->partner_table;
        $query = \DB::table($tableName);

        // Apply dynamic filters from partner_filter_conditions
        if ($this->partner_filter_conditions && is_array($this->partner_filter_conditions)) {
            foreach ($this->partner_filter_conditions as $method => $params) {
                if ($method === 'whereNotNull' && is_string($params)) {
                    $query->whereNotNull($params);
                } elseif ($method === 'whereNull' && is_string($params)) {
                    $query->whereNull($params);
                } elseif ($method === 'where' && is_array($params) && count($params) >= 2) {
                    $query->where($params[0], $params[1], $params[2] ?? null);
                }
            }
        }

        return $query
            ->whereNull('deleted_at') // Exclude soft-deleted
            ->orderBy('name')
            ->get();
    }
}
