<?php
/**
 * CUSTOMER DISPUTE DETAILS - CONVERSATION THREAD
 * File: customer/dispute-details.php
 */

session_start();
require_once '../app/Core/init.php';

// Authentication check
if (!isset($_SESSION['user_id']) || !isset($_SESSION['user_type']) || $_SESSION['user_type'] !== 'customer') {
    header('Location: ../index.php');
    exit();
}

// Page variables
$page_title = "Disputes";
$active_menu = "disputes";

$customer_user_id = Auth::getUserId();
$db = Database::getInstance();
$dispute_id = $_GET['id'] ?? 0;

// Get customer ID
$customer_sql = "SELECT id FROM customers WHERE user_id = ?";
$customer = $db->fetch($customer_sql, [$customer_user_id]);

if (!$customer) {
    flash('error', 'Customer profile not found', 'danger');
    redirect('../index.php');
}

$customer_id = $customer['id'];

// Get dispute details - SIMPLIFIED QUERY
$dispute_sql = "SELECT d.*, 
                o.order_number, o.id as order_id,
                i.title as item_title,
                v.business_name as vendor_name
                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
                WHERE d.id = ?";

$dispute = $db->fetch($dispute_sql, [$dispute_id]);

if (!$dispute) {
    flash('error', 'Dispute not found', 'danger');
    redirect('disputes.php');
    exit;
}

// Verify this customer owns the order
$order_check_sql = "SELECT customer_id FROM orders WHERE id = ?";
$order_check = $db->fetch($order_check_sql, [$dispute['order_id']]);

if (!$order_check || $order_check['customer_id'] != $customer_id) {
    flash('error', 'Unauthorized access', 'danger');
    redirect('disputes.php');
    exit;
}

// Get messages
$disputeMessage = new DisputeMessage();
$messages = $disputeMessage->getByDisputeId($dispute_id);

// Mark messages as read
$disputeMessage->markAsRead($dispute_id, 'customer');

$page_title = 'Dispute Details - ' . APP_NAME;
include '../templates/layouts/customer/head.php';
?>

<body class="fixed sidebar-mini">
    <div class="wrapper">
        <!-- Sidebar -->
        <nav class="sidebar">
            <div class="sidebar-header">
                <?php include '../templates/layouts/customer/navbar.php'; ?>
            </div>
        </nav>

        <!-- Page Content -->
        <div class="content-wrapper">

        <div class="main-content">
        <?php include '../templates/layouts/customer/header.php'; ?>
                    <!-- Body Content -->
                    <div class="body-content">
                        <div class="decoration blur-2"></div>
                        <div class="decoration blur-3"></div>
                        <div class="container-xxl">
                    
    <div class="page-header mb-4">
        <a href="disputes.php" class="btn btn-secondary btn-sm mb-2">
            <i class="fas fa-arrow-left"></i> Back to Reports
        </a>
        <h1><i class="fas fa-exclamation-triangle"></i> Dispute #<?= esc($dispute['dispute_number']) ?></h1>
    </div>

    <div class="row">
        <!-- Dispute Info -->
        <div class="col-md-4 mb-4">
            <div class="card">
                <div class="card-header bg-warning">
                    <h5 class="mb-0">Dispute Information</h5>
                </div>
                <div class="card-body">
                    <p>
                        <strong>Status:</strong><br>
                        <?php
                        $status_colors = ['open' => 'warning', 'under_review' => 'info', 'resolved' => 'success', 'closed' => 'secondary'];
                        $color = $status_colors[$dispute['status']] ?? 'secondary';
                        ?>
                        <span class="badge bg-<?= $color ?>"><?= ucfirst(str_replace('_', ' ', $dispute['status'])) ?></span>
                    </p>
                    <p>
                        <strong>Issue Type:</strong><br>
                        <?php
                        $type_labels = ['damage' => 'Item Damaged', 'non_return' => 'Non-Return', 'quality' => 'Quality Issue', 'overcharge' => 'Overcharge', 'other' => 'Other'];
                        echo $type_labels[$dispute['dispute_type']] ?? ucwords($dispute['dispute_type']);
                        ?>
                    </p>
                    <p>
                        <strong>Order:</strong><br>
                        <a href="order-details.php?id=<?= $dispute['order_id'] ?>"><?= esc($dispute['order_number']) ?></a>
                    </p>
                    <p>
                        <strong>Item:</strong><br>
                        <?= esc($dispute['item_title']) ?>
                    </p>
                    <p>
                        <strong>Vendor:</strong><br>
                        <?= esc($dispute['vendor_name']) ?>
                    </p>
                    <?php if ($dispute['amount_involved']): ?>
                        <p>
                            <strong>Amount Claimed:</strong><br>
                            ₦<?= number_format($dispute['amount_involved'], 2) ?>
                        </p>
                    <?php endif; ?>
                    <p>
                        <strong>Reported:</strong><br>
                        <?= date('M d, Y H:i', strtotime($dispute['created_at'])) ?>
                    </p>
                    
                    <hr>
                    <p class="mb-2"><strong>Description:</strong></p>
                    <div class="alert alert-light">
                        <?= nl2br(esc($dispute['description'])) ?>
                    </div>
                    
                    <!-- Initial Evidence Photos -->
                    <?php if (!empty($dispute['evidence_files'])): ?>
                        <?php 
                        $files = json_decode($dispute['evidence_files'], true); 
                        if ($files && is_array($files) && count($files) > 0):
                        ?>
                            <hr>
                            <p class="mb-2"><strong>Initial Evidence:</strong></p>
                            <div class="row g-2">
                                <?php foreach ($files as $file): ?>
                                    <div class="col-6">
                                        <a href="../uploads/<?= esc($file) ?>" target="_blank" data-lightbox="evidence">
                                            <img src="../uploads/<?= esc($file) ?>" class="img-fluid rounded" alt="Evidence" style="max-height: 80px; width: 100%; object-fit: cover;">
                                        </a>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Conversation Thread -->
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">Conversation</h5>
                </div>
                <div class="card-body" style="max-height: 500px; overflow-y: auto;" id="messagesContainer">
                    <?php if (empty($messages)): ?>
                        <p class="text-muted text-center">No messages yet</p>
                    <?php else: ?>
                        <?php foreach ($messages as $msg): ?>
                            <?php
                            $is_me = $msg['sender_type'] === 'customer';
                            $align = $is_me ? 'text-end' : 'text-start';
                            $bg = $is_me ? 'bg-primary text-white' : ($msg['sender_type'] === 'admin' ? 'bg-warning' : 'bg-light');
                            $sender_label = $is_me ? 'You' : ($msg['sender_type'] === 'vendor' ? $dispute['vendor_name'] : 'Admin');
                            ?>
                            <div class="mb-3 <?= $align ?>">
                                <div class="d-inline-block <?= $bg ?> rounded p-3" style="max-width: 70%;">
                                    <strong><?= esc($sender_label) ?></strong><br>
                                    <p class="mb-1"><?= nl2br(esc($msg['message'])) ?></p>
                                    
                                    <?php if (!empty($msg['attachments'])): ?>
                                    <?php 
                                    // Split comma-separated values into array
                                    $files = explode(',', $msg['attachments']);
                                    
                                    if ($files && is_array($files) && count($files) > 0):
                                    ?>
                                        <div class="mt-2">
                                            <div class="row g-1">
                                                <?php foreach ($files as $file): ?>
                                                    <?php if (trim($file)): // Skip empty values ?>
                                                        <div class="col-6">
                                                            <a href="../uploads/<?= esc(trim($file)) ?>" target="_blank">
                                                                <img src="../uploads/<?= esc(trim($file)) ?>" 
                                                                    class="img-fluid rounded" 
                                                                    alt="Attachment" 
                                                                    style="max-height: 80px; width: 100%; object-fit: cover;">
                                                            </a>
                                                        </div>
                                                    <?php endif; ?>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>
                                <?php endif; ?>
                                    
                                    <small class="<?= $is_me ? 'text-white-50' : 'text-muted' ?>">
                                        <?= date('M d, H:i', strtotime($msg['created_at'])) ?>
                                    </small>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                
                <?php if ($dispute['status'] !== 'closed' && $dispute['status'] !== 'resolved'): ?>
                    <div class="card-footer">
                        <form id="replyForm" enctype="multipart/form-data">
                            <input type="hidden" name="dispute_id" value="<?= $dispute_id ?>">
                            <input type="hidden" name="sender_type" value="customer">
                            
                            <div class="mb-3">
                                <textarea name="message" class="form-control" rows="3" placeholder="Type your message..." required></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label class="btn btn-sm btn-outline-secondary">
                                    <i class="fas fa-camera"></i> Attach Photos
                                    <input type="file" name="attachments[]" class="d-none" id="fileInput" multiple accept="image/*" onchange="previewImages(this)">
                                </label>
                                <small class="text-muted ms-2">Images will be compressed automatically</small>
                                <div id="imagePreview" class="mt-2"></div>
                            </div>
                            
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-paper-plane"></i> Send Message
                            </button>
                        </form>
                    </div>
                <?php else: ?>
                    <div class="card-footer bg-light">
                        <p class="mb-0 text-center">
                            <i class="fas fa-lock"></i> This dispute has been <?= $dispute['status'] ?>
                        </p>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include '../templates/layouts/customer/footer.php'; ?>

<script>
function previewImages(input) {
    const preview = document.getElementById('imagePreview');
    preview.innerHTML = '';
    
    if (input.files) {
        Array.from(input.files).forEach((file, index) => {
            const reader = new FileReader();
            reader.onload = function(e) {
                const div = document.createElement('div');
                div.className = 'd-inline-block me-2 mb-2 position-relative';
                div.innerHTML = `
                    <img src="${e.target.result}" class="rounded" style="height: 60px; width: 60px; object-fit: cover;">
                    <span class="badge bg-success position-absolute top-0 end-0">${index + 1}</span>
                `;
                preview.appendChild(div);
            };
            reader.readAsDataURL(file);
        });
    }
}

document.getElementById('replyForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const submitBtn = this.querySelector('button[type="submit"]');
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Sending...';
    
    fetch('../api/send-dispute-message.php', {
        method: 'POST',
        body: formData
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            location.reload();
        } else {
            alert('Error: ' + data.error);
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="fas fa-paper-plane"></i> Send Message';
        }
    });
});

// Auto scroll to bottom
var container = document.getElementById('messagesContainer');
if (container) {
    container.scrollTop = container.scrollHeight;
}
</script>