<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;


class Company extends Model
{
    use HasFactory;
    use SoftDeletes;

    public function __construct()
    {
        $this->setTenant();
    }

    protected $fillable = [
        'name',
        'business_name',
        'logo',
        'phone',
        'email',
        'pec',
        'costitution_date',
        'address',
        'zip',
        'city_id',
        'country_id',
        'operational_headquarters',
        'fiscal_code',
        'vat',           
        'sdi_code',
        'ateco_code',            
        'enabled',
    ];

    public function country()
    {
        return $this->belongsTo(\App\Models\Country::class);
    }

    public function city()
    {
        return $this->belongsTo(\App\Models\City::class);
    }

    public function activities()
    {
        return $this->hasMany(\App\Models\CompanyActivity::class);
    }

    public function rates()
    {
        return $this->hasMany(\App\Models\CompanyActivity::class);
    }

    public function services()
    {
        return $this->hasMany(\App\Models\CompanyActivity::class);
    }

    function setTenant()
    {
        $user = auth()->user();

        if ($user) {
            Log::info('Setting database connection', [
                'database' => $user->tenant_database,
                'username' => $user->tenant_username,
                // 'password' => $user->tenant_password
            ]);

            $connection = [
                'driver' => 'mysql',
                'host' => '127.0.0.1',
                'port' => '3306',
                'database' => $user->tenant_database,
                'username' => $user->tenant_username,
                // 'password' => $user->tenant_password,
            ];

            config(['database.connections.tenant' => $connection]);

            config(['database.default' => 'tenant']);
            DB::purge('tenant');
            DB::reconnect('tenant');

            session(['currentClient' => $user->tenant_database]);

            session(['db_connection' => $connection]);

            Log::info('Current database after setup: ' . DB::connection()->getDatabaseName());
            Log::info('Current default connection: ' . DB::getDefaultConnection());
        }
    }
}
