<?php
/**
 * Dispute Message Model
 * File: app/Models/DisputeMessage.php
 * Handles dispute conversation messages
 */

class DisputeMessage {
    private $db;
    
    public function __construct() {
        $this->db = Database::getInstance();
    }
    
    /**
     * Add message to dispute
     */
    public function create($data) {
        $sql = "INSERT INTO dispute_messages 
                (dispute_id, sender_type, sender_id, message, attachments, created_at)
                VALUES (?, ?, ?, ?, ?, NOW())";
        
        $attachments = isset($data['attachments']) ? json_encode($data['attachments']) : null;
        
        $result = $this->db->execute($sql, [
            $data['dispute_id'],
            $data['sender_type'],
            $data['sender_id'],
            $data['message'],
            $attachments
        ]);
        
        if ($result) {
            // Update last response info in disputes table
            $this->db->execute(
                "UPDATE disputes 
                 SET last_response_by = ?, last_response_at = NOW(), updated_at = NOW()
                 WHERE id = ?",
                [$data['sender_type'], $data['dispute_id']]
            );
            
            return $this->db->lastInsertId();
        }
        
        return false;
    }
    
    /**
     * Get all messages for a dispute
     */
    public function getByDisputeId($dispute_id) {
        $sql = "SELECT dm.*, 
                CASE 
                    WHEN dm.sender_type = 'customer' THEN CONCAT(c.first_name, ' ', c.last_name)
                    WHEN dm.sender_type = 'vendor' THEN v.business_name
                    WHEN dm.sender_type = 'admin' THEN 'Admin Team'
                END as sender_name,
                CASE 
                    WHEN dm.sender_type = 'customer' THEN cu.email
                    WHEN dm.sender_type = 'vendor' THEN vu.email
                    WHEN dm.sender_type = 'admin' THEN au.email
                END as sender_email
                FROM dispute_messages dm
                LEFT JOIN customers c ON dm.sender_type = 'customer' AND dm.sender_id = c.user_id
                LEFT JOIN users cu ON c.user_id = cu.id
                LEFT JOIN vendors v ON dm.sender_type = 'vendor' AND dm.sender_id = v.user_id
                LEFT JOIN users vu ON v.user_id = vu.id
                LEFT JOIN users au ON dm.sender_type = 'admin' AND dm.sender_id = au.id
                WHERE dm.dispute_id = ?
                ORDER BY dm.created_at ASC";
        
        return $this->db->fetchAll($sql, [$dispute_id]);
    }
    
    /**
     * Mark messages as read
     */
    public function markAsRead($dispute_id, $reader_type) {
        $field = "is_read_by_{$reader_type}";
        
        $sql = "UPDATE dispute_messages 
                SET {$field} = 1 
                WHERE dispute_id = ? AND sender_type != ?";
        
        return $this->db->execute($sql, [$dispute_id, $reader_type]);
    }
    
    /**
     * Get unread count for user
     */
    public function getUnreadCount($dispute_id, $user_type) {
        $field = "is_read_by_{$user_type}";
        
        $sql = "SELECT COUNT(*) as count 
                FROM dispute_messages 
                WHERE dispute_id = ? 
                AND sender_type != ? 
                AND {$field} = 0";
        
        $result = $this->db->fetch($sql, [$dispute_id, $user_type]);
        return $result['count'] ?? 0;
    }
    
    /**
     * Get latest message
     */
    public function getLatest($dispute_id) {
        $sql = "SELECT * FROM dispute_messages 
                WHERE dispute_id = ? 
                ORDER BY created_at DESC 
                LIMIT 1";
        
        return $this->db->fetch($sql, [$dispute_id]);
    }
    
    /**
     * Delete message
     */
    public function delete($id) {
        $sql = "DELETE FROM dispute_messages WHERE id = ?";
        return $this->db->execute($sql, [$id]);
    }
}
