<?php
namespace App\Repositories;

use App\Database\Connection;
use App\Utils\Logger;
use PDO;
use PDOException;

class SatisfactionRepository
{
    private $db;

    public function __construct(Connection $db)
    {
        $this->db = $db;
    }

    public function save($contactId, $score, $note, $registeredBy)
    {
        $pdo = $this->db->getPdo();
        $stmt = $pdo->prepare("INSERT INTO customer_satisfactions 
                              (contact_didar_id, satisfaction_score, satisfaction_note, registered_by_didar_id, register_date)
                              VALUES (?, ?, ?, ?, NOW())");
        return $stmt->execute([$contactId, $score, $note, $registeredBy]);
    }

    public function findByContact($contactId)
    {
        $pdo = $this->db->getPdo();
        $hasDisplayName = $this->db->hasColumn('users', 'display_name');
        $ownerNameField = $hasDisplayName 
            ? "u.display_name" 
            : "COALESCE(CONCAT(u.first_name, ' ', u.last_name), '')";
        
        $stmt = $pdo->prepare("SELECT cs.*, $ownerNameField as registered_by_name 
                              FROM customer_satisfactions cs
                              LEFT JOIN users u ON cs.registered_by_didar_id = u.didar_user_id
                              WHERE cs.contact_didar_id = ? 
                              ORDER BY cs.register_date DESC");
        $stmt->execute([$contactId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
}

