<?php
declare(strict_types=1);

namespace App\Modules\Branches\Models;

use App\Core\Model;
use App\Core\App;

class Branch extends Model
{
    protected static string $table = 'branches';
    protected static string $primaryKey = 'id';
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $dispatchEvents = true;

    protected static array $fillable = [
        'branch_code', 'name_ar', 'name_en', 'address', 'phone',
        'manager_name', 'is_active', 'member_count_cache',
    ];

    public static function allActive(): array
    {
        $db = App::getInstance()->db();
        return $db->select("SELECT * FROM branches WHERE is_active = 1 ORDER BY name_ar");
    }

    public static function getByCode(string $code): ?static
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne("SELECT * FROM branches WHERE branch_code = ?", [$code]);
        if (!$row) {
            return null;
        }
        $instance = new static($row);
        $instance->exists = true;
        return $instance;
    }

    public function getMemberCount(): int
    {
        $db = App::getInstance()->db();
        try {
            if (!$db->tableExists('members')) {
                return 0;
            }
            $result = $db->selectOne(
                "SELECT COUNT(*) as cnt FROM members WHERE branch_id = ? AND is_archived = 0",
                [$this->id]
            );
            return (int) ($result['cnt'] ?? 0);
        } catch (\Throwable $e) {
            return (int) ($this->member_count_cache ?? 0);
        }
    }

    public function getEmployeeCount(): int
    {
        $db = App::getInstance()->db();
        $result = $db->selectOne(
            "SELECT COUNT(*) as cnt FROM employees WHERE branch_id = ? AND is_archived = 0 AND is_active = 1",
            [$this->id]
        );
        return (int) ($result['cnt'] ?? 0);
    }
}