<?php

namespace Modules\Services\Models;

use core\Model;
use core\Database;

class Service extends Model
{
    protected string $table = 'services';
    protected string $primaryKey = 'id';
    protected array $fillable = [
        'name',
        'slug',
        'category_id',
        'description',
        'duration_minutes',
        'price',
        'cost_price',
        'tax_percent',
        'color',
        'commission_type',
        'commission_value',
        'is_active',
        'created_at',
        'updated_at',
    ];

    protected array $guarded = ['id'];
    protected array $casts = [
        'duration_minutes' => 'int',
        'price' => 'float',
        'cost_price' => 'float',
        'tax_percent' => 'float',
        'commission_value' => 'float',
        'is_active' => 'bool',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
    ];

    public function search(string $query): array
    {
        if (empty($query)) {
            return [];
        }

        $db = Database::getInstance();
        $searchTerm = '%' . $query . '%';

        return $db->table($this->table . ' s')
            ->select('s.id, s.name, s.slug, s.duration_minutes, s.price, s.color, s.is_active,
                     sc.name as category_name')
            ->leftJoin('service_categories sc', 's.category_id', '=', 'sc.id')
            ->where('s.deleted_at', 'IS', null)
            ->where(function ($q) use ($searchTerm) {
                $q->where('s.name', 'LIKE', $searchTerm)
                  ->orWhere('s.description', 'LIKE', $searchTerm);
            })
            ->orderBy('s.name', 'ASC')
            ->limit(20)
            ->get();
    }

    public function getByCategory(int $categoryId): array
    {
        $db = Database::getInstance();

        return $db->table($this->table)
            ->where('category_id', $categoryId)
            ->where('is_active', 1)
            ->where('deleted_at', 'IS', null)
            ->orderBy('name', 'ASC')
            ->get();
    }

    public function getActive(): array
    {
        $db = Database::getInstance();

        return $db->table($this->table . ' s')
            ->select('s.*, sc.name as category_name')
            ->leftJoin('service_categories sc', 's.category_id', '=', 'sc.id')
            ->where('s.is_active', 1)
            ->where('s.deleted_at', 'IS', null)
            ->orderBy('s.name', 'ASC')
            ->get();
    }

    public function getCategories(): array
    {
        $db = Database::getInstance();

        return $db->table('service_categories')
            ->where('is_active', 1)
            ->where('deleted_at', 'IS', null)
            ->orderBy('sort_order', 'ASC')
            ->get();
    }
}
