<?php
/**
 * Model Client (utilisateur final)
 * mySupport - Plateforme de Service Client Intelligent
 */

namespace App\Models;

use Core\Model;

class Client extends Model
{
    protected string $table = 'clients';

    public function findOrCreate(int $entrepriseId, array $data): int
    {
        $existingClient = null;
        
        if (!empty($data['whatsapp_id'])) {
            $existingClient = $this->db->fetch(
                "SELECT * FROM {$this->table} WHERE entreprise_id = :eid AND whatsapp_id = :wid",
                ['eid' => $entrepriseId, 'wid' => $data['whatsapp_id']]
            );
        } elseif (!empty($data['telephone'])) {
            $existingClient = $this->db->fetch(
                "SELECT * FROM {$this->table} WHERE entreprise_id = :eid AND telephone = :tel",
                ['eid' => $entrepriseId, 'tel' => $data['telephone']]
            );
        } elseif (!empty($data['email'])) {
            $existingClient = $this->db->fetch(
                "SELECT * FROM {$this->table} WHERE entreprise_id = :eid AND email = :email",
                ['eid' => $entrepriseId, 'email' => $data['email']]
            );
        }
        
        if ($existingClient) {
            return (int) $existingClient['id'];
        }
        
        $data['entreprise_id'] = $entrepriseId;
        return $this->create($data);
    }

    public function getByEntreprise(int $entrepriseId, int $limit = 100): array
    {
        $sql = "SELECT c.*, 
                       (SELECT COUNT(*) FROM conversations WHERE client_id = c.id) as nb_conversations
                FROM {$this->table} c
                WHERE c.entreprise_id = :entreprise_id
                ORDER BY c.created_at DESC
                LIMIT {$limit}";
        
        return $this->db->fetchAll($sql, ['entreprise_id' => $entrepriseId]);
    }

    public function getConversations(int $clientId): array
    {
        $sql = "SELECT * FROM conversations 
                WHERE client_id = :client_id 
                ORDER BY created_at DESC";
        
        return $this->db->fetchAll($sql, ['client_id' => $clientId]);
    }

    public function updateLanguePreferee(int $clientId, string $langue): bool
    {
        return $this->update($clientId, ['langue_preferee' => $langue]) > 0;
    }

    public function findByPhone(int $entrepriseId, string $telephone): ?array
    {
        $sql = "SELECT * FROM {$this->table} 
                WHERE entreprise_id = :eid AND telephone = :tel 
                LIMIT 1";
        
        $result = $this->db->fetch($sql, ['eid' => $entrepriseId, 'tel' => $telephone]);
        return $result ?: null;
    }
}
