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

namespace App\Models;

use Core\Model;

class Alerte extends Model
{
    protected string $table = 'alertes';

    public function getByEntreprise(int $entrepriseId, bool $unreadOnly = false): array
    {
        $sql = "SELECT * FROM {$this->table} 
                WHERE entreprise_id = :entreprise_id";
        $params = ['entreprise_id' => $entrepriseId];
        
        if ($unreadOnly) {
            $sql .= " AND is_read = FALSE";
        }
        
        $sql .= " ORDER BY created_at DESC";
        
        return $this->db->fetchAll($sql, $params);
    }

    public function getUnreadCount(int $entrepriseId): int
    {
        $sql = "SELECT COUNT(*) as count FROM {$this->table} 
                WHERE entreprise_id = :entreprise_id AND is_read = FALSE";
        $result = $this->db->fetch($sql, ['entreprise_id' => $entrepriseId]);
        return (int) ($result['count'] ?? 0);
    }

    public function markAsRead(int $alerteId): bool
    {
        return $this->update($alerteId, ['is_read' => true]) > 0;
    }

    public function markAllAsRead(int $entrepriseId): int
    {
        $sql = "UPDATE {$this->table} SET is_read = TRUE 
                WHERE entreprise_id = :entreprise_id AND is_read = FALSE";
        return $this->db->query($sql, ['entreprise_id' => $entrepriseId])->rowCount();
    }

    public function resolve(int $alerteId, int $userId): bool
    {
        return $this->update($alerteId, [
            'is_resolved' => true,
            'resolved_by' => $userId,
            'resolved_at' => date('Y-m-d H:i:s')
        ]) > 0;
    }

    public function createAlerte(int $entrepriseId, string $type, string $titre, string $description, string $severite = 'info', array $donnees = []): int
    {
        return $this->create([
            'entreprise_id' => $entrepriseId,
            'type' => $type,
            'titre' => $titre,
            'description' => $description,
            'severite' => $severite,
            'donnees' => json_encode($donnees)
        ]);
    }

    public function getAllForSuperAdmin(): array
    {
        $sql = "SELECT a.*, e.nom as entreprise_nom 
                FROM {$this->table} a
                LEFT JOIN entreprises e ON a.entreprise_id = e.id
                ORDER BY a.created_at DESC
                LIMIT 100";
        
        return $this->db->fetchAll($sql);
    }
}
