<?php
/**
 * Model Entreprise
 * mySupport - Plateforme de Service Client Intelligent
 */

namespace App\Models;

use Core\Model;

class Entreprise extends Model
{
    protected string $table = 'entreprises';

    public function findBySlug(string $slug): ?array
    {
        return $this->findBy('slug', $slug);
    }

    public function findByToken(string $token): ?array
    {
        return $this->findBy('widget_token', $token);
    }

    public function getAllActive(): array
    {
        $sql = "SELECT * FROM {$this->table} WHERE is_active = TRUE ORDER BY nom ASC";
        return $this->db->fetchAll($sql);
    }

    public function createEntreprise(array $data): int
    {
        $data['slug'] = $this->generateSlug($data['nom']);
        $data['widget_token'] = $this->generateToken();
        return $this->create($data);
    }

    public function generateSlug(string $nom): string
    {
        $slug = strtolower(trim($nom));
        $slug = preg_replace('/[^a-z0-9-]/', '-', $slug);
        $slug = preg_replace('/-+/', '-', $slug);
        $slug = trim($slug, '-');
        
        $baseSlug = $slug;
        $counter = 1;
        
        while ($this->exists('slug', $slug)) {
            $slug = $baseSlug . '-' . $counter;
            $counter++;
        }
        
        return $slug;
    }

    public function generateToken(): string
    {
        do {
            $token = bin2hex(random_bytes(32));
        } while ($this->exists('widget_token', $token));
        
        return $token;
    }

    public function toggleActive(int $id): bool
    {
        $entreprise = $this->find($id);
        if (!$entreprise) {
            return false;
        }
        
        return $this->update($id, [
            'is_active' => !$entreprise['is_active']
        ]) > 0;
    }

    public function getStatistiques(): array
    {
        $sql = "SELECT 
                    COUNT(*) as total,
                    SUM(CASE WHEN is_active = TRUE THEN 1 ELSE 0 END) as actives,
                    SUM(CASE WHEN type_abonnement = 'basic' THEN 1 ELSE 0 END) as basic,
                    SUM(CASE WHEN type_abonnement = 'pro' THEN 1 ELSE 0 END) as pro,
                    SUM(CASE WHEN type_abonnement = 'enterprise' THEN 1 ELSE 0 END) as enterprise
                FROM {$this->table}";
        
        return $this->db->fetch($sql);
    }

    public function getLanguesActives(int $id): array
    {
        $entreprise = $this->find($id);
        if (!$entreprise) {
            return [];
        }
        return json_decode($entreprise['langues_actives'], true) ?? [];
    }

    public function getCanauxActifs(int $id): array
    {
        $entreprise = $this->find($id);
        if (!$entreprise) {
            return [];
        }
        return json_decode($entreprise['canaux_actifs'], true) ?? [];
    }
    
    public function findByApiKey(string $apiKey): ?array
    {
        return $this->findBy('api_key', $apiKey);
    }
    
    public function generateApiKey(): string
    {
        do {
            $key = 'ms_' . bin2hex(random_bytes(16));
        } while ($this->exists('api_key', $key));
        
        return $key;
    }
    
    public function regenerateApiKey(int $id): ?string
    {
        $newKey = $this->generateApiKey();
        $updated = $this->update($id, ['api_key' => $newKey]);
        
        return $updated > 0 ? $newKey : null;
    }
}
