<?php
/**
 * ADMIN DISPUTE DETAILS - MEDIATION INTERFACE
 * File: admin/dispute-details.php
 */

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

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

// Get dispute details
$dispute_sql = "SELECT d.*, 
                o.order_number, o.id as order_id, o.total_amount,
                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,
                c.phone as customer_phone,
                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 = ?";

$dispute = $db->fetch($dispute_sql, [$dispute_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 by admin
$disputeMessage->markAsRead($dispute_id, 'admin');

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

<div class="main-content">
    <?php include '../templates/layouts/admin/header.php'; ?>

    <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 All Disputes
        </a>
        <h1><i class="fas fa-gavel"></i> Mediate Dispute #<?= esc($dispute['dispute_number']) ?></h1>
    </div>

    <div class="row">
        <!-- Dispute Info Sidebar -->
        <div class="col-md-4 mb-4">
            <div class="card mb-3">
                <div class="card-header bg-danger text-white">
                    <h5 class="mb-0"><i class="fas fa-info-circle"></i> Dispute Information</h5>
                </div>
                <div class="card-body">
                    <p>
                        <strong>Status:</strong><br>
                        <?php
                        $status_colors = [
                            'open' => 'danger',
                            'under_review' => 'info',
                            'resolved' => 'success',
                            'closed' => 'secondary'
                        ];
                        $color = $status_colors[$dispute['status']] ?? 'secondary';
                        ?>
                        <span class="badge bg-<?= $color ?> fs-6"><?= ucfirst(str_replace('_', ' ', $dispute['status'])) ?></span>
                    </p>
                    
                    <p>
                        <strong>Reported By:</strong><br>
                        <span class="badge bg-secondary"><?= ucfirst($dispute['raised_by_type']) ?></span>
                    </p>
                    
                    <p>
                        <strong>Issue Type:</strong><br>
                        <?php
                        $type_labels = ['damage' => 'Damaged', 'non_return' => 'Non-Return', 'quality' => 'Quality', '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'] ?>" target="_blank">
                            <?= esc($dispute['order_number']) ?>
                            <i class="fas fa-external-link-alt fa-xs"></i>
                        </a>
                    </p>
                    
                    <p>
                        <strong>Item:</strong><br>
                        <?= esc($dispute['item_title']) ?>
                    </p>
                    
                    <p>
                        <strong>Order Amount:</strong><br>
                        ₦<?= number_format($dispute['total_amount'], 2) ?>
                    </p>
                    
                    <?php if ($dispute['amount_involved']): ?>
                        <p>
                            <strong>Amount Claimed:</strong><br>
                            <span class="text-danger fw-bold">
                                ₦<?= number_format($dispute['amount_involved'], 2) ?>
                            </span>
                        </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 
                        $evidence = json_decode($dispute['evidence_files'], true); 
                        if ($evidence && is_array($evidence) && count($evidence) > 0):
                        ?>
                            <hr>
                            <p class="mb-2"><strong>Initial Evidence:</strong></p>
                            <div class="row g-2">
                                <?php foreach ($evidence as $file): ?>
                                    <div class="col-6">
                                        <a href="../uploads/<?= esc($file) ?>" target="_blank">
                                            <img src="../uploads/<?= esc($file) ?>" class="img-fluid rounded" alt="Evidence" style="max-height: 80px; object-fit: cover;">
                                        </a>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Parties Information -->
            <div class="card mb-3">
                <div class="card-header bg-info text-white">
                    <h6 class="mb-0"><i class="fas fa-users"></i> Parties Involved</h6>
                </div>
                <div class="card-body">
                    <p>
                        <strong><i class="fas fa-user"></i> Customer:</strong><br>
                        <?= esc($dispute['customer_name']) ?><br>
                        <small class="text-muted">
                            <i class="fas fa-envelope"></i> <?= esc($dispute['customer_email']) ?><br>
                            <i class="fas fa-phone"></i> <?= esc($dispute['customer_phone']) ?>
                        </small>
                    </p>
                    
                    <hr>
                    
                    <p class="mb-0">
                        <strong><i class="fas fa-store"></i> Vendor:</strong><br>
                        <?= esc($dispute['vendor_name']) ?><br>
                        <small class="text-muted">
                            <i class="fas fa-envelope"></i> <?= esc($dispute['vendor_email']) ?>
                        </small>
                    </p>
                </div>
            </div>
            
            <!-- Admin Actions -->
            <div class="card">
                <div class="card-header bg-dark text-white">
                    <h6 class="mb-0"><i class="fas fa-tools"></i> Admin Actions</h6>
                </div>
                <div class="card-body">
                    <?php if ($dispute['status'] === 'open'): ?>
                        <button class="btn btn-info w-100 mb-2" onclick="updateStatus('under_review')">
                            <i class="fas fa-play"></i> Mark Under Review
                        </button>
                    <?php endif; ?>
                    
                    <?php if (in_array($dispute['status'], ['open', 'under_review'])): ?>
                        <button class="btn btn-success w-100 mb-2" onclick="updateStatus('resolved')">
                            <i class="fas fa-check-circle"></i> Mark Resolved
                        </button>
                        <button class="btn btn-secondary w-100" onclick="updateStatus('closed')">
                            <i class="fas fa-lock"></i> Close Dispute
                        </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Conversation Thread -->
        <div class="col-md-8">
            <div class="card">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="fas fa-comments"></i> Conversation & Mediation</h5>
                </div>
                <div class="card-body" style="max-height: 500px; overflow-y: auto; background: #f8f9fa;" id="messagesContainer">
                    <?php if (empty($messages)): ?>
                        <div class="text-center py-5">
                            <i class="fas fa-comments fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No messages yet. Be the first to mediate this dispute.</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($messages as $msg): ?>
                            <?php
                            $is_admin = $msg['sender_type'] === 'admin';
                            $is_customer = $msg['sender_type'] === 'customer';
                            $is_vendor = $msg['sender_type'] === 'vendor';
                            
                            if ($is_admin) {
                                $align = 'text-center';
                                $bg = 'bg-warning text-dark';
                                $sender_label = 'Admin (You)';
                            } elseif ($is_customer) {
                                $align = 'text-start';
                                $bg = 'bg-primary text-white';
                                $sender_label = $dispute['customer_name'] . ' (Customer)';
                            } else {
                                $align = 'text-end';
                                $bg = 'bg-success text-white';
                                $sender_label = $dispute['vendor_name'] . ' (Vendor)';
                            }
                            ?>
                            <div class="mb-3 <?= $align ?>">
                                <div class="d-inline-block <?= $bg ?> rounded p-3 shadow-sm" style="<?= $is_admin ? 'max-width: 90%;' : 'max-width: 70%;' ?>">
                                    <strong><i class="fas fa-user-circle"></i> <?= esc($sender_label) ?></strong><br>
                                    <p class="mb-1 mt-2"><?= 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_admin ? 'text-muted' : ($is_customer ? 'text-white-50' : 'text-white-50') ?>">
                                        <i class="far fa-clock"></i> <?= date('M d, H:i', strtotime($msg['created_at'])) ?>
                                    </small>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
                
                <?php if ($dispute['status'] !== 'closed'): ?>
                    <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="admin">
                            
                            <div class="mb-3">
                                <label class="form-label fw-bold">Admin Mediation Message:</label>
                                <textarea name="message" class="form-control" rows="4" 
                                          placeholder="Enter your mediation message to both parties..." required></textarea>
                                <small class="text-muted">This message will be visible to both customer and vendor.</small>
                            </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</small>
                                <div id="imagePreview" class="mt-2"></div>
                            </div>
                            
                            <div class="d-flex justify-content-end">
                                <button type="submit" class="btn btn-warning">
                                    <i class="fas fa-gavel"></i> Send Mediation Message
                                </button>
                            </div>
                        </form>
                    </div>
                <?php else: ?>
                    <div class="card-footer bg-secondary text-white text-center">
                        <i class="fas fa-lock"></i> This dispute has been closed. No further messages can be sent.
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>

<?php include '../templates/layouts/admin/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();
    
    var formData = new FormData(this);
    var submitBtn = this.querySelector('button[type="submit"]');
    var originalHtml = submitBtn.innerHTML;
    
    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 = originalHtml;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Failed to send message. Please try again.');
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalHtml;
    });
});

function updateStatus(newStatus) {
    var statusLabel = newStatus.replace('_', ' ');
    if (confirm('Update dispute status to "' + statusLabel + '"?\n\nBoth parties will be notified.')) {
        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) {
                alert('✓ Dispute status updated to: ' + statusLabel);
                location.reload();
            } else {
                alert('✗ Error: ' + data.error);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Failed to update status');
        });
    }
}

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