<?php
/**
 * VENDOR DISPUTE DETAILS - CONVERSATION THREAD
 * File: vendor/dispute-details.php
 */

require_once '../app/Core/init.php';
Auth::requireVendor();

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

// Get vendor details
$vendor = new Vendor();
$vendor_data = $vendor->getByUserId($vendor_user_id);

if (!$vendor_data) {
    flash('error', 'Please complete your profile first.', 'danger');
    redirect('vendor/profile.php');
}

// Get dispute details
$dispute_sql = "SELECT d.*, 
                o.order_number, o.id as order_id,
                i.title as item_title,
                CONCAT(c.first_name, ' ', c.last_name) as customer_name,
                c.phone as customer_phone,
                u.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 customers c ON o.customer_id = c.id
                JOIN users u ON c.user_id = u.id
                WHERE d.id = ? AND o.vendor_id = ?";

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

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

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

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

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

<div class="main-content">
    <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 Disputes
        </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', 'in_progress' => '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>Reported By:</strong><br>
                        <?= ucfirst($dispute['raised_by_type']) ?>
                    </p>
                    <p>
                        <strong>Issue Type:</strong><br>
                        <?= ucwords(str_replace('_', ' ', $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>Customer:</strong><br>
                        <?= esc($dispute['customer_name']) ?><br>
                        <small class="text-muted"><?= esc($dispute['customer_email']) ?></small>
                    </p>
                    <?php if ($dispute['amount_involved']): ?>
                        <p>
                            <strong>Amount Involved:</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>
                    
                    <?php if ($dispute['status'] === 'open'): ?>
                        <button class="btn btn-info btn-sm w-100 mb-2" onclick="updateStatus('in_progress')">
                            <i class="fas fa-play"></i> Mark In Progress
                        </button>
                    <?php endif; ?>
                    
                    <?php if (in_array($dispute['status'], ['open', 'in_progress'])): ?>
                        <button class="btn btn-success btn-sm w-100" onclick="updateStatus('resolved')">
                            <i class="fas fa-check"></i> Mark Resolved
                        </button>
                    <?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'] === 'vendor';
                            $align = $is_me ? 'text-end' : 'text-start';
                            $bg = $is_me ? 'bg-success text-white' : 'bg-light';
                            
                            if ($msg['sender_type'] === 'customer') {
                                $sender_label = $dispute['customer_name'];
                            } elseif ($msg['sender_type'] === 'admin') {
                                $sender_label = 'Admin';
                            } else {
                                $sender_label = 'You';
                            }
                            ?>
                            <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 echo?>
                                                            <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="vendor">
                            
                            <div class="mb-3">
                                <textarea name="message" class="form-control" rows="3" placeholder="Type your response..." required></textarea>
                            </div>
                            
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <label class="btn btn-sm btn-outline-secondary">
                                        <i class="fas fa-paperclip"></i> Attach File
                                        <input type="file" name="attachments[]" class="d-none" multiple accept="image/*,.pdf">
                                    </label>
                                </div>
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-paper-plane"></i> Send Response
                                </button>
                            </div>
                        </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/vendor/footer.php'; ?>

<script>
document.getElementById('replyForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    var formData = new FormData(this);
    var 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 Response';
        }
    });
});

function updateStatus(newStatus) {
    if (confirm('Update dispute status to ' + newStatus.replace('_', ' ') + '?')) {
        fetch('../api/update-dispute-status.php', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: 'dispute_id=<?= $dispute_id ?>&status=' + newStatus
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                location.reload();
            } else {
                alert('Error: ' + data.error);
            }
        });
    }
}

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