<?php
/**
 * VENDOR ITEM DETAILS PAGE
 * File: vendor/item-details.php
 * View detailed information about a specific rental item (Vendor View)
 */

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

// Require vendor authentication
Auth::requireVendor();

$page_title = "Item Details";
$active_menu = "items";

// Get item ID
$item_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$item_id) {
    flash('error', 'Invalid item ID', 'danger');
    redirect('items.php');
}

// Initialize models
$db = Database::getInstance();
$vendor = new Vendor();

// Get vendor details
$vendor_id = Auth::id();
$vendor_data = $vendor->getByUserId($vendor_id);

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

// Get item details - ensure it belongs to the current vendor
$item_sql = "SELECT 
    i.*,
    c.name as category_name,
    c.icon as category_icon,
    (SELECT COUNT(*) FROM orders WHERE item_id = i.id) as total_orders,
    (SELECT COUNT(*) FROM orders WHERE item_id = i.id AND status = 'completed') as completed_orders,
    (SELECT COUNT(*) FROM orders WHERE item_id = i.id AND status = 'ongoing') as active_orders,
    (SELECT COALESCE(SUM(total_amount), 0) FROM orders WHERE item_id = i.id AND status = 'completed') as total_earnings
FROM items i
LEFT JOIN categories c ON i.category_id = c.id
WHERE i.id = ? AND i.vendor_id = ?";

$item = $db->fetch($item_sql, [$item_id, $vendor_data['id']]);

if (!$item) {
    flash('error', 'Item not found or you do not have permission to view it', 'danger');
    redirect('items.php');
}

// Get item images
$images_sql = "SELECT * FROM item_images WHERE item_id = ? ORDER BY display_order ASC";
$item_images = $db->fetchAll($images_sql, [$item_id]);

// Get item reviews with customer details
$reviews_sql = "SELECT r.*, CONCAT(c.first_name, ' ', c.last_name) as customer_name,
                c.profile_picture as customer_avatar
                FROM reviews r
                LEFT JOIN customers c ON r.customer_id = c.id
                WHERE r.item_id = ?
                ORDER BY r.created_at DESC
                LIMIT 20";
$reviews = $db->fetchAll($reviews_sql, [$item_id]);

// Get item availability calendar
$availability_sql = "SELECT * FROM availability_calendar 
                     WHERE item_id = ? AND date >= CURDATE()
                     ORDER BY date ASC
                     LIMIT 30";
$availability = $db->fetchAll($availability_sql, [$item_id]);

// Get recent orders for this item
$orders_sql = "SELECT o.*, CONCAT(c.first_name, ' ', c.last_name) as customer_name,
               c.phone as customer_phone
               FROM orders o
               LEFT JOIN customers c ON o.customer_id = c.id
               WHERE o.item_id = ?
               ORDER BY o.created_at DESC
               LIMIT 10";
$recent_orders = $db->fetchAll($orders_sql, [$item_id]);

// Calculate statistics
$stats_sql = "SELECT 
              COALESCE(COUNT(*), 0) as total_reviews,
              COALESCE(ROUND(AVG(rating), 1), 0) as average_rating,
              COALESCE(COUNT(CASE WHEN rating = 5 THEN 1 END), 0) as five_star,
              COALESCE(COUNT(CASE WHEN rating = 4 THEN 1 END), 0) as four_star,
              COALESCE(COUNT(CASE WHEN rating = 3 THEN 1 END), 0) as three_star,
              COALESCE(COUNT(CASE WHEN rating = 2 THEN 1 END), 0) as two_star,
              COALESCE(COUNT(CASE WHEN rating = 1 THEN 1 END), 0) as one_star
              FROM reviews 
              WHERE item_id = ?";
$rating_stats = $db->fetch($stats_sql, [$item_id]) ?: [
    'total_reviews' => 0,
    'average_rating' => 0,
    'five_star' => 0,
    'four_star' => 0,
    'three_star' => 0,
    'two_star' => 0,
    'one_star' => 0
];

// Handle flash messages
$flash_message = flash('message');

include '../templates/layouts/vendor/header.php';
?>

<div class="main-content">
    <div class="page-header">
        <div class="header-left">
            <h1><i class="fas fa-box"></i> Item Details</h1>
            <p class="text-muted">Manage and monitor your rental item</p>
        </div>
        <div class="header-right">
            <a href="item-form.php?id=<?= $item_id ?>" class="btn btn-primary">
                <i class="fas fa-edit"></i> Edit Item
            </a>
            <a href="items.php" class="btn btn-secondary">
                <i class="fas fa-arrow-left"></i> Back to Items
            </a>
        </div>
    </div>

    <!-- Flash Messages -->
    <?php if ($flash_message): ?>
        <div class="alert alert-<?= $flash_message['type'] ?>">
            <?= Security::escapeOutput($flash_message['message']) ?>
        </div>
    <?php endif; ?>
    
    <!-- Item Overview Cards -->
    <div class="stats-grid mb-4">
        <!-- Item Status Card -->
        <div class="stat-card">
            <div class="stat-icon <?= $item['approval_status'] === 'approved' ? 'bg-success' : ($item['approval_status'] === 'pending' ? 'bg-warning' : 'bg-danger') ?>">
                <i class="fas fa-<?= $item['approval_status'] === 'approved' ? 'check-circle' : ($item['approval_status'] === 'pending' ? 'clock' : 'times-circle') ?>"></i>
            </div>
            <div class="stat-details">
                <h3><?= ucfirst($item['approval_status']) ?></h3>
                <p>Approval Status</p>
            </div>
        </div>
        
        <!-- Total Orders Card -->
        <div class="stat-card">
            <div class="stat-icon bg-primary">
                <i class="fas fa-shopping-bag"></i>
            </div>
            <div class="stat-details">
                <h3><?= number_format($item['total_orders']) ?></h3>
                <p>Total Orders</p>
            </div>
        </div>
        
        <!-- Active Orders Card -->
        <div class="stat-card">
            <div class="stat-icon bg-info">
                <i class="fas fa-sync"></i>
            </div>
            <div class="stat-details">
                <h3><?= number_format($item['active_orders']) ?></h3>
                <p>Active Rentals</p>
            </div>
        </div>
        
        <!-- Total Earnings Card -->
        <div class="stat-card">
            <div class="stat-icon bg-success">
                <i class="fas fa-money-bill-wave"></i>
            </div>
            <div class="stat-details">
                <h3><?= format_money($item['total_earnings']) ?></h3>
                <p>Total Earnings</p>
            </div>
        </div>
    </div>
    
    <div class="row">
        <div class="col-lg-8">
            <!-- Item Information -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-info-circle"></i> Item Information</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Title</strong></label>
                            <div><?= Security::escapeOutput($item['title']) ?></div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Category</strong></label>
                            <div>
                                <?php if (!empty($item['category_icon'])): ?>
                                    <i class="<?= Security::escapeOutput($item['category_icon']) ?>"></i>
                                <?php endif; ?>
                                <?= Security::escapeOutput($item['category_name']) ?>
                            </div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Price Per Day</strong></label>
                            <div class="text-success fw-bold"><?= format_money($item['price_per_day']) ?></div>
                            <?php if (($item['security_deposit'] ?? 0) > 0): ?>
                                <small class="text-muted">Security Deposit: <?= format_money($item['security_deposit']) ?></small>
                            <?php endif; ?>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Location</strong></label>
                            <div>
                                <?= Security::escapeOutput($item['location']) ?><br>
                                <small class="text-muted"><?= Security::escapeOutput($item['city'] . ', ' . $item['state']) ?></small>
                            </div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Condition</strong></label>
                            <div><?= ucfirst(str_replace('_', ' ', $item['condition_status'])) ?></div>
                        </div>
                        
                        <div class="col-md-6 mb-3">
                            <label class="form-label"><strong>Quantity</strong></label>
                            <div>
                                Available: <strong><?= $item['available_quantity'] ?></strong> / 
                                Total: <strong><?= $item['quantity'] ?></strong>
                            </div>
                        </div>
                        
                        <div class="col-12 mb-3">
                            <label class="form-label"><strong>Description</strong></label>
                            <div class="border rounded p-3 bg-light">
                                <?= nl2br(Security::escapeOutput($item['description'])) ?>
                            </div>
                        </div>
                        
                        <?php if (!empty($item['rejection_reason'])): ?>
                            <div class="col-12">
                                <div class="alert alert-danger">
                                    <h6><i class="fas fa-exclamation-triangle"></i> Rejection Reason</h6>
                                    <p class="mb-0"><?= Security::escapeOutput($item['rejection_reason']) ?></p>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Features & Terms -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-list"></i> Features & Terms</h5>
                </div>
                <div class="card-body">
                    <div class="row">
                        <?php if (!empty($item['features'])): ?>
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><strong>Features</strong></label>
                                <div class="border rounded p-3 bg-light">
                                    <?= nl2br(Security::escapeOutput($item['features'])) ?>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($item['terms_and_conditions'])): ?>
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><strong>Terms & Conditions</strong></label>
                                <div class="border rounded p-3 bg-light">
                                    <?= nl2br(Security::escapeOutput($item['terms_and_conditions'])) ?>
                                </div>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="col-lg-4">
            <!-- Item Images -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-images"></i> Item Images</h5>
                </div>
                <div class="card-body">
                    <?php if (empty($item_images) && empty($item['main_image'])): ?>
                        <p class="text-muted text-center">No images uploaded</p>
                    <?php else: ?>
                        <div class="row g-2">
                            <!-- Main Image -->
                            <?php if (!empty($item['main_image'])): ?>
                                <div class="col-12">
                                    <div class="position-relative">
                                        <img src="<?= upload('items/' . $item['main_image']) ?>" 
                                             alt="Main Image"
                                             class="img-fluid rounded"
                                             style="width: 100%; height: 200px; object-fit: cover;">
                                        <span class="badge bg-primary position-absolute top-0 start-0 m-2">Main</span>
                                    </div>
                                </div>
                            <?php endif; ?>
                            
                            <!-- Additional Images -->
                            <?php foreach ($item_images as $image): ?>
                                <div class="col-6">
                                    <img src="<?= upload($image['image_path']) ?>" 
                                         alt="Item Image"
                                         class="img-fluid rounded"
                                         style="width: 100%; height: 120px; object-fit: cover;">
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>

            <!-- Quick Stats -->
            <div class="card mb-4">
                <div class="card-header">
                    <h5 class="mb-0"><i class="fas fa-chart-bar"></i> Quick Stats</h5>
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label class="form-label"><strong>Views</strong></label>
                        <div><?= number_format($item['views_count']) ?> views</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label"><strong>Rating</strong></label>
                        <div class="d-flex align-items-center">
                            <div class="text-warning me-2">
                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                    <i class="fas fa-star <?= $i <= ($rating_stats['average_rating'] ?? 0) ? '' : 'text-light' ?>"></i>
                                <?php endfor; ?>
                            </div>
                            <span>(<?= number_format($rating_stats['average_rating'] ?? 0, 1) ?>)</span>
                        </div>
                        <small class="text-muted">Based on <?= $rating_stats['total_reviews'] ?> reviews</small>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label"><strong>Created</strong></label>
                        <div><?= format_date($item['created_at']) ?></div>
                    </div>
                    
                    <?php if (!empty($item['updated_at'])): ?>
                        <div class="mb-3">
                            <label class="form-label"><strong>Last Updated</strong></label>
                            <div><?= format_date($item['updated_at']) ?></div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($item['approval_date'])): ?>
                        <div>
                            <label class="form-label"><strong>Approved</strong></label>
                            <div><?= format_date($item['approval_date']) ?></div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <!-- Tabs Section -->
    <div class="card">
        <div class="card-header">
            <ul class="nav nav-tabs card-header-tabs" id="itemTabs" role="tablist">
                <li class="nav-item" role="presentation">
                    <button class="nav-link active" id="reviews-tab" data-bs-toggle="tab" data-bs-target="#reviews" type="button" role="tab">
                        <i class="fas fa-comments"></i> Reviews (<?= count($reviews) ?>)
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="orders-tab" data-bs-toggle="tab" data-bs-target="#orders" type="button" role="tab">
                        <i class="fas fa-shopping-cart"></i> Recent Orders (<?= count($recent_orders) ?>)
                    </button>
                </li>
                <li class="nav-item" role="presentation">
                    <button class="nav-link" id="availability-tab" data-bs-toggle="tab" data-bs-target="#availability" type="button" role="tab">
                        <i class="fas fa-calendar"></i> Availability
                    </button>
                </li>
            </ul>
        </div>
        <div class="card-body">
            <div class="tab-content" id="itemTabsContent">
                <!-- Reviews Tab -->
                <div class="tab-pane fade show active" id="reviews" role="tabpanel">
                    <?php if (empty($reviews)): ?>
                        <div class="text-center py-4">
                            <i class="fas fa-comments fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No reviews yet</p>
                        </div>
                    <?php else: ?>
                        <?php foreach ($reviews as $review): ?>
                            <div class="border-bottom pb-3 mb-3">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <div class="d-flex align-items-center">
                                        <?php if (!empty($review['customer_avatar'])): ?>
                                            <img src="<?= upload($review['customer_avatar']) ?>" 
                                                 alt="<?= Security::escapeOutput($review['customer_name']) ?>"
                                                 class="rounded-circle me-3" width="40" height="40">
                                        <?php else: ?>
                                            <div class="rounded-circle bg-primary text-white d-flex align-items-center justify-content-center me-3" style="width: 40px; height: 40px;">
                                                <?= strtoupper(substr($review['customer_name'], 0, 2)) ?>
                                            </div>
                                        <?php endif; ?>
                                        <div>
                                            <strong><?= Security::escapeOutput($review['customer_name']) ?></strong>
                                            <div class="text-warning">
                                                <?php for ($i = 1; $i <= 5; $i++): ?>
                                                    <i class="fas fa-star <?= $i <= $review['rating'] ? '' : 'text-light' ?>"></i>
                                                <?php endfor; ?>
                                            </div>
                                        </div>
                                    </div>
                                    <small class="text-muted"><?= format_date($review['created_at']) ?></small>
                                </div>
                                <p class="mb-2"><?= Security::escapeOutput($review['review']) ?></p>
                                
                                <?php if (!empty($review['vendor_reply'])): ?>
                                    <div class="bg-light p-3 rounded mt-2">
                                        <strong>Your Reply:</strong>
                                        <p class="mb-1"><?= Security::escapeOutput($review['vendor_reply']) ?></p>
                                        <small class="text-muted">Replied on <?= format_date($review['vendor_replied_at']) ?></small>
                                    </div>
                                <?php else: ?>
                                    <button class="btn btn-sm btn-outline-primary mt-2" 
                                            onclick="showReplyForm(<?= $review['id'] ?>)">
                                        <i class="fas fa-reply"></i> Reply
                                    </button>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <!-- Orders Tab -->
                <div class="tab-pane fade" id="orders" role="tabpanel">
                    <?php if (empty($recent_orders)): ?>
                        <div class="text-center py-4">
                            <i class="fas fa-shopping-cart fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No orders yet</p>
                        </div>
                    <?php else: ?>
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Order #</th>
                                        <th>Customer</th>
                                        <th>Period</th>
                                        <th>Amount</th>
                                        <th>Status</th>
                                        <th>Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recent_orders as $order): ?>
                                        <tr>
                                            <td>
                                                <a href="order-details.php?id=<?= $order['id'] ?>" class="text-decoration-none">
                                                    <?= Security::escapeOutput($order['order_number']) ?>
                                                </a>
                                            </td>
                                            <td><?= Security::escapeOutput($order['customer_name']) ?></td>
                                            <td>
                                                <small>
                                                    <?= format_date($order['start_date'], 'M d') ?> - 
                                                    <?= format_date($order['end_date'], 'M d') ?>
                                                    <br>(<?= $order['rental_days'] ?> days)
                                                </small>
                                            </td>
                                            <td><strong><?= format_money($order['total_amount']) ?></strong></td>
                                            <td>
                                                <?= format_status_badge($order['status']) ?>
                                            </td>
                                            <td><small><?= format_date($order['created_at'], 'M d, Y') ?></small></td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- Availability Tab -->
                <div class="tab-pane fade" id="availability" role="tabpanel">
                    <?php if (empty($availability)): ?>
                        <div class="text-center py-4">
                            <i class="fas fa-calendar fa-3x text-muted mb-3"></i>
                            <p class="text-muted">No availability data</p>
                        </div>
                    <?php else: ?>
                        <div class="row">
                            <?php foreach ($availability as $day): ?>
                                <div class="col-md-3 col-sm-4 col-6 mb-3">
                                    <div class="card">
                                        <div class="card-body text-center p-3">
                                            <div class="fw-bold"><?= format_date($day['date'], 'D, M d') ?></div>
                                            <div class="mt-2">
                                                <?= format_status_badge($day['status']) ?>
                                            </div>
                                            <?php if ($day['quantity_booked'] > 0): ?>
                                                <small class="text-muted d-block mt-1">
                                                    Qty: <?= $day['quantity_booked'] ?>
                                                </small>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Reply Modal -->
<div class="modal fade" id="replyModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Reply to Review</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form id="replyForm" method="POST" action="review-reply.php">
                <div class="modal-body">
                    <input type="hidden" name="review_id" id="reviewId">
                    <div class="mb-3">
                        <label class="form-label">Your Reply</label>
                        <textarea name="vendor_reply" class="form-control" rows="4" required></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Send Reply</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function showReplyForm(reviewId) {
    document.getElementById('reviewId').value = reviewId;
    var replyModal = new bootstrap.Modal(document.getElementById('replyModal'));
    replyModal.show();
}

// Auto-hide success messages
setTimeout(function() {
    const alerts = document.querySelectorAll('.alert-success');
    alerts.forEach(alert => {
        alert.style.transition = 'opacity 0.5s';
        alert.style.opacity = '0';
        setTimeout(() => alert.remove(), 500);
    });
}, 3000);
</script>

<style>
.stat-card {
    background: white;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 15px;
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 24px;
}

.stat-details h3 {
    margin: 0;
    font-size: 24px;
    font-weight: 700;
}

.stat-details p {
    margin: 0;
    color: #666;
    font-size: 14px;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
}
</style>

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