<?php
/**
 * API: Raise Dispute - COMPLETE FIXED VERSION WITH PROPER JSON
 * File: api/raise-dispute.php
 */

// Start output buffering to prevent any output before JSON
ob_start();

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

// Clean any output that happened during init
ob_end_clean();

// Start fresh buffer
ob_start();

// Set headers
header('Content-Type: application/json');
header('Cache-Control: no-cache, must-revalidate');

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

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

$order_id = $_POST['order_id'] ?? 0;
$dispute_type = $_POST['dispute_type'] ?? '';
$description = $_POST['description'] ?? '';
$amount_involved = $_POST['amount_involved'] ?? null;
$raised_by_type = $_POST['raised_by_type'] ?? '';

try {
    $db = Database::getInstance();
    $user_id = Auth::getUserId();
    
    // Validate inputs
    if (empty($order_id) || empty($dispute_type) || empty($description)) {
        throw new Exception("All fields are required");
    }
    
    // Get order details
    $order_sql = "SELECT o.*, 
                  i.title as item_title,
                  v.business_name as vendor_name, v.user_id as vendor_user_id,
                  vu.email as vendor_email,
                  CONCAT(c.first_name, ' ', c.last_name) as customer_name, c.user_id as customer_user_id,
                  cu.email as customer_email
                  FROM orders o
                  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 o.id = ?";
    
    $order = $db->fetch($order_sql, [$order_id]);
    
    if (!$order) {
        throw new Exception("Order not found");
    }
    
    // Verify user can raise dispute
    if ($raised_by_type === 'customer' && $order['customer_user_id'] != $user_id) {
        throw new Exception("Unauthorized");
    }
    if ($raised_by_type === 'vendor' && $order['vendor_user_id'] != $user_id) {
        throw new Exception("Unauthorized");
    }
    
    // Handle file uploads with image compression
    $evidence_files = [];
    if (!empty($_FILES['evidence']['name'][0])) {
        $upload_dir = '../public/uploads/disputes/';
        if (!is_dir($upload_dir)) {
            mkdir($upload_dir, 0777, true);
        }
        
        foreach ($_FILES['evidence']['name'] as $key => $name) {
            if ($_FILES['evidence']['error'][$key] === UPLOAD_ERR_OK) {
                $tmp_name = $_FILES['evidence']['tmp_name'][$key];
                $file_ext = strtolower(pathinfo($name, PATHINFO_EXTENSION));
                $new_name = uniqid('dispute_') . '.' . $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) {
                                $evidence_files[] = 'disputes/' . $new_name;
                            }
                        } else {
                            // Failed to create image resource, save as-is
                            if (move_uploaded_file($tmp_name, $destination)) {
                                $evidence_files[] = 'disputes/' . $new_name;
                            }
                        }
                    } else {
                        // Not a valid image, save as-is
                        if (move_uploaded_file($tmp_name, $destination)) {
                            $evidence_files[] = 'disputes/' . $new_name;
                        }
                    }
                } else {
                    // Not an image file (PDF, doc, etc.) - save as-is
                    if (move_uploaded_file($tmp_name, $destination)) {
                        $evidence_files[] = 'disputes/' . $new_name;
                    }
                }
            }
        }
    }
    
    $db->beginTransaction();
    
    // Generate dispute number
    $dispute_number = 'DSP-' . date('Ymd') . '-' . strtoupper(substr(uniqid(), -6));
    
    // Create dispute record
    $dispute_sql = "INSERT INTO disputes 
                    (dispute_number, order_id, raised_by, raised_by_type, dispute_type, 
                     description, amount_involved, evidence_files, status, created_at, updated_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'open', NOW(), NOW())";
    
    $db->execute($dispute_sql, [
        $dispute_number,
        $order_id,
        $user_id,
        $raised_by_type,
        $dispute_type,
        $description,
        $amount_involved,
        !empty($evidence_files) ? implode(',', $evidence_files) : null
    ]);
    
    $dispute_id = $db->lastInsertId();
    
    // Add initial message
    $disputeMessage = new DisputeMessage();
    $message_data = [
        'dispute_id' => $dispute_id,
        'sender_type' => $raised_by_type,
        'sender_id' => $user_id,
        'message' => $description,
        'attachments' => !empty($evidence_files) ? implode(',', $evidence_files) : null
    ];
    
    $disputeMessage->create($message_data);
    
    // Update order
    $db->execute(
        "UPDATE orders 
         SET has_active_dispute = 1, 
             dispute_count = dispute_count + 1 
         WHERE id = ?",
        [$order_id]
    );
    
    $db->commit();
    
    // Send emails (suppress errors)
    try {
        $mailer = new Mailer();
        
        $issue_labels = [
            'damage' => 'Item Damaged',
            'non_return' => 'Non-Return Issue',
            'quality' => 'Quality Issue',
            'overcharge' => 'Overcharge',
            'late_return' => 'Late Return',
            'payment_issue' => 'Payment Issue',
            'misuse' => 'Item Misuse',
            'other' => 'Other Issue'
        ];
        
        $issue_label = $issue_labels[$dispute_type] ?? ucwords(str_replace('_', ' ', $dispute_type));
        
        // Email to opposite party (use dispute-raised.php template)
        if ($raised_by_type === 'customer') {
            // Customer raised dispute - notify vendor
            $recipient_name = $order['vendor_name'];
            $reporter_name = $order['customer_name'];
            $reporter_type = 'customer';
            $recipient_email = $order['vendor_email'];
            $dashboard_url = APP_URL . '/vendor/disputes.php?id=' . $dispute_id;
            
        } else {
            // Vendor raised dispute - notify customer
            $recipient_name = $order['customer_name'];
            $reporter_name = $order['vendor_name'];
            $reporter_type = 'vendor';
            $recipient_email = $order['customer_email'];
            $dashboard_url = APP_URL . '/customer/disputes.php?id=' . $dispute_id;
        }
        
        // Set all required variables for dispute-raised.php
        $order_number = $order['order_number'];
        $item_title = $order['item_title'];
        $issue_type = $issue_label;
        // $description already set from POST
        // $amount_involved already set from POST
        // $dispute_number already generated
        
        // Get email body using existing dispute-raised.php template
        ob_start();
        include ROOT_PATH . '/templates/email/dispute-raised.php';
        $email_body = ob_get_clean();
        
        // Send to customer/vendor
        $subject = "⚠️ Issue Reported on Order #{$order['order_number']}";
        $mailer->send($recipient_email, $subject, $email_body);
        
        // Email admin using existing dispute-admin-notification.php template
        $admin_email = defined('ADMIN_EMAIL') ? ADMIN_EMAIL : 'admin@rentidium.ng';
        
        // Set admin-specific variables
        $customer_name = $order['customer_name'];
        $vendor_name = $order['vendor_name'];
        $admin_url = APP_URL . '/admin/disputes.php?id=' . $dispute_id;
        // Keep other variables: $dispute_number, $reporter_name, $reporter_type, $order_number, $item_title, $issue_type, $description, $amount_involved
        
        // Get admin email body
        ob_start();
        include ROOT_PATH . '/templates/email/dispute-admin-notification.php';
        $admin_email_body = ob_get_clean();
        
        // Send to admin
        $admin_subject = "🚨 NEW DISPUTE: {$dispute_number} - {$issue_label}";
        $mailer->send($admin_email, $admin_subject, $admin_email_body);
        
    } catch (Exception $e) {
        // Email failed but dispute created successfully
        error_log("Email notification failed: " . $e->getMessage());
    }
    
    // Clean buffer and output JSON
    ob_end_clean();
    
    echo json_encode([
        'success' => true,
        'message' => 'Issue reported successfully. Relevant parties have been notified.',
        'dispute_id' => $dispute_id,
        'dispute_number' => $dispute_number
    ]);
    
} catch (Exception $e) {
    if (isset($db) && $db->inTransaction()) {
        $db->rollback();
    }
    
    error_log("Raise dispute error: " . $e->getMessage());
    
    // Clean buffer and output JSON
    ob_end_clean();
    
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}

exit;