<?php
/**
 * API: Send Dispute Message - ALL ISSUES FIXED
 * File: api/send-dispute-message.php
 */

require_once '../app/Core/init.php';

header('Content-Type: application/json');

if (!Auth::check()) {
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Invalid request']);
    exit;
}

$dispute_id = $_POST['dispute_id'] ?? 0;
$message = trim($_POST['message'] ?? '');
$sender_type = $_POST['sender_type'] ?? ''; // 'customer', 'vendor', or 'admin'

try {
    if (empty($dispute_id) || empty($message) || empty($sender_type)) {
        throw new Exception("All fields are required");
    }
    
    $db = Database::getInstance();
    $user_id = Auth::getUserId();
    
    // Verify user can send message to this dispute
    $dispute_sql = "SELECT d.*, 
                    o.customer_id, o.vendor_id,
                    v.user_id as vendor_user_id,
                    c.user_id as customer_user_id
                    FROM disputes d
                    JOIN orders o ON d.order_id = o.id
                    LEFT JOIN vendors v ON o.vendor_id = v.id
                    LEFT JOIN customers c ON o.customer_id = c.id
                    WHERE d.id = ?";
    
    $dispute = $db->fetch($dispute_sql, [$dispute_id]);
    
    if (!$dispute) {
        throw new Exception("Dispute not found");
    }
    
    // Check if dispute is closed or resolved - no further replies allowed
    if (in_array($dispute['status'], ['closed', 'resolved'])) {
        throw new Exception("This dispute has been " . $dispute['status'] . ". No further replies allowed.");
    }
    
    // Verify authorization
    if ($sender_type === 'customer' && $dispute['customer_user_id'] != $user_id) {
        throw new Exception("Unauthorized");
    }
    if ($sender_type === 'vendor' && $dispute['vendor_user_id'] != $user_id) {
        throw new Exception("Unauthorized");
    }
    if ($sender_type === 'admin' && !Auth::isAdmin()) {
        throw new Exception("Unauthorized");
    }
    
    // Handle file uploads with improved image compression
    $attachments = [];
    if (!empty($_FILES['attachments']['name'][0])) {
        $upload_dir = '../public/uploads/disputes/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        foreach ($_FILES['attachments']['name'] as $key => $name) {
            if ($_FILES['attachments']['error'][$key] === UPLOAD_ERR_OK) {
                $tmp_name = $_FILES['attachments']['tmp_name'][$key];
                $file_ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
                $new_name = 'dispute_' . $dispute_id . '_' . time() . '_' . $key . '.' . $file_ext;
                $destination = $upload_dir . $new_name;
                
                // Check if it's an image file
                $image_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
                
                if (in_array($file_ext, $image_extensions)) {
                    // It's an image - compress it
                    $image_info = getimagesize($tmp_name);
                    if ($image_info !== false) {
                        $width = $image_info[0];
                        $height = $image_info[1];
                        $mime_type = $image_info['mime'];
                        
                        // Create image resource from file
                        switch ($mime_type) {
                            case 'image/jpeg':
                                $source = imagecreatefromjpeg($tmp_name);
                                break;
                            case 'image/png':
                                $source = imagecreatefrompng($tmp_name);
                                break;
                            case 'image/gif':
                                $source = imagecreatefromgif($tmp_name);
                                break;
                            case 'image/webp':
                                $source = imagecreatefromwebp($tmp_name);
                                break;
                            default:
                                $source = null;
                        }
                        
                        if ($source) {
                            // Resize if image is too large (max width: 1920px)
                            $max_width = 1920;
                            $max_height = 1920;
                            
                            if ($width > $max_width || $height > $max_height) {
                                // Calculate new dimensions maintaining aspect ratio
                                $ratio = min($max_width / $width, $max_height / $height);
                                $new_width = round($width * $ratio);
                                $new_height = round($height * $ratio);
                            } else {
                                // Keep original dimensions
                                $new_width = $width;
                                $new_height = $height;
                            }
                            
                            // Create new image with new dimensions
                            $resized = imagecreatetruecolor($new_width, $new_height);
                            
                            // Preserve transparency for PNG and GIF
                            if ($file_ext === 'png' || $file_ext === 'gif') {
                                imagealphablending($resized, false);
                                imagesavealpha($resized, true);
                                $transparent = imagecolorallocatealpha($resized, 0, 0, 0, 127);
                                imagefilledrectangle($resized, 0, 0, $new_width, $new_height, $transparent);
                            }
                            
                            // Copy and resample
                            imagecopyresampled($resized, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
                            
                            // Save with compression
                            $saved = false;
                            switch ($file_ext) {
                                case 'jpg':
                                case 'jpeg':
                                    // Quality: 85 (high quality, good compression)
                                    $saved = imagejpeg($resized, $destination, 85);
                                    break;
                                case 'png':
                                    // Compression: 6 (0=none, 9=max compression)
                                    $saved = imagepng($resized, $destination, 6);
                                    break;
                                case 'gif':
                                    $saved = imagegif($resized, $destination);
                                    break;
                                case 'webp':
                                    // Quality: 85
                                    $saved = imagewebp($resized, $destination, 85);
                                    break;
                            }
                            
                            // Free memory
                            imagedestroy($source);
                            imagedestroy($resized);
                            
                            if ($saved) {
                                $attachments[] = 'disputes/' . $new_name;
                            }
                        } else {
                            // Failed to create image resource, save as-is
                            if (move_uploaded_file($tmp_name, $destination)) {
                                $attachments[] = 'disputes/' . $new_name;
                            }
                        }
                    } else {
                        // Not a valid image, save as-is
                        if (move_uploaded_file($tmp_name, $destination)) {
                            $attachments[] = 'disputes/' . $new_name;
                        }
                    }
                } else {
                    // Not an image file (PDF, doc, etc.) - save as-is
                    if (move_uploaded_file($tmp_name, $destination)) {
                        $attachments[] = 'disputes/' . $new_name;
                    }
                }
            }
        }
    }
    
    // Add message to conversation
    $disputeMessage = new DisputeMessage();
    $message_data = [
        'dispute_id' => $dispute_id,
        'sender_type' => $sender_type,
        'sender_id' => $user_id,
        'message' => $message,
        'attachments' => !empty($attachments) ? implode(',', $attachments) : null
    ];
    
    $disputeMessage->create($message_data);
    
    // FIXED: Don't change status on reply - keep it 'open'
    // Status should only be changed by admin through update-dispute-status.php
    
    // Send email notifications
    $mailer = new Mailer();
    
    // Get full dispute details
    $full_dispute_sql = "SELECT d.*,
                         o.order_number,
                         i.title as item_title,
                         v.business_name as vendor_name,
                         vu.email as vendor_email,
                         CONCAT(c.first_name, ' ', c.last_name) as customer_name,
                         cu.email as customer_email
                         FROM disputes d
                         JOIN orders o ON d.order_id = o.id
                         JOIN items i ON o.item_id = i.id
                         JOIN vendors v ON o.vendor_id = v.id
                         JOIN users vu ON v.user_id = vu.id
                         JOIN customers c ON o.customer_id = c.id
                         JOIN users cu ON c.user_id = cu.id
                         WHERE d.id = ?";
    
    $full_dispute = $db->fetch($full_dispute_sql, [$dispute_id]);
    
    $sender_name = $sender_type === 'customer' ? $full_dispute['customer_name'] : 
                   ($sender_type === 'vendor' ? $full_dispute['vendor_name'] : 'Admin');
    
    // Notify customer (if sender is not customer) using template
    if ($sender_type !== 'customer') {
        $subject = "New Message on Dispute {$full_dispute['dispute_number']} - " . APP_NAME;
        $body = $mailer->getTemplate('dispute-message', [
            'recipient_name' => $full_dispute['customer_name'],
            'sender_name' => $sender_name,
            'sender_type' => $sender_type,
            'dispute_number' => $full_dispute['dispute_number'],
            'order_number' => $full_dispute['order_number'],
            'item_title' => $full_dispute['item_title'],
            'message' => $message,
            'dashboard_url' => APP_URL . '/customer/dispute-details.php?id=' . $dispute_id,
            'app_name' => APP_NAME
        ]);
        $mailer->send($full_dispute['customer_email'], $subject, $body);
    }
    
    // Notify vendor (if sender is not vendor) using template
    if ($sender_type !== 'vendor') {
        $subject = "New Message on Dispute {$full_dispute['dispute_number']} - " . APP_NAME;
        $body = $mailer->getTemplate('dispute-message', [
            'recipient_name' => $full_dispute['vendor_name'],
            'sender_name' => $sender_name,
            'sender_type' => $sender_type,
            'dispute_number' => $full_dispute['dispute_number'],
            'order_number' => $full_dispute['order_number'],
            'item_title' => $full_dispute['item_title'],
            'message' => $message,
            'dashboard_url' => APP_URL . '/vendor/dispute-details.php?id=' . $dispute_id,
            'app_name' => APP_NAME
        ]);
        $mailer->send($full_dispute['vendor_email'], $subject, $body);
    }
    
    // Notify admin (if sender is not admin) using template
    if ($sender_type !== 'admin') {
        $admin_email = defined('ADMIN_EMAIL') ? ADMIN_EMAIL : 'admin@rentidium.ng';
        $subject = "New Activity on Dispute {$full_dispute['dispute_number']} - " . APP_NAME;
        $body = $mailer->getTemplate('dispute-admin-notification', [
            'dispute_number' => $full_dispute['dispute_number'],
            'reporter_name' => $sender_name,
            'reporter_type' => $sender_type,
            'order_number' => $full_dispute['order_number'],
            'item_title' => $full_dispute['item_title'],
            'customer_name' => $full_dispute['customer_name'],
            'vendor_name' => $full_dispute['vendor_name'],
            'issue_type' => 'New Message',
            'description' => $message,
            'admin_url' => APP_URL . '/admin/dispute-details.php?id=' . $dispute_id,
            'app_name' => APP_NAME
        ]);
        $mailer->send($admin_email, $subject, $body);
    }
    
    echo json_encode([
        'success' => true,
        'message' => 'Message sent successfully'
    ]);
    
} catch (Exception $e) {
    error_log("Send dispute message error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}