<?php
/**
 * ADMIN ITEM DETAILS PAGE
 * File: admin/item-details.php
 * View detailed information about a specific rental item
 */

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

// Check admin authentication
Auth::requireAdmin();

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

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

if (!$item_id) {
    header('Location: items.php');
    exit;
}

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

// First, let's get the basic item data
$basic_item_sql = "SELECT * FROM items WHERE id = ?";
$basic_item = $db->fetch($basic_item_sql, [$item_id]);

if (!$basic_item) {
    header('Location: items.php');
    exit;
}

$item_sql = "SELECT 
    i.*,
    v.business_name as vendor_name,
    v.phone as vendor_phone,
    u.email as vendor_email,  -- Get email from users table, not vendors
    c.name as category_name,
    c.icon as category_icon,
    COALESCE(w.balance, 0) as vendor_balance,
    (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
FROM items i
LEFT JOIN vendors v ON i.vendor_id = v.id
LEFT JOIN users u ON v.user_id = u.id  -- Join users to get vendor email
LEFT JOIN categories c ON i.category_id = c.id
LEFT JOIN wallets w ON v.user_id = w.user_id
WHERE i.id = ?";

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

if (!$item) {
    header('Location: items.php');
    exit;
}

// 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
               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 item actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    switch ($action) {
        case 'approve':
            $reason = trim($_POST['reason'] ?? '');
            
            try {
                $update_sql = "UPDATE items 
                              SET approval_status = 'approved',
                                  status = 'approved',
                                  approved_by = ?,
                                  approval_date = NOW(),
                                  rejection_reason = NULL
                              WHERE id = ?";
                $db->execute($update_sql, [$_SESSION['admin_user_id'], $item_id]);
                
                flash('message', ['type' => 'success', 'message' => 'Item approved successfully']);
                header('Location: item-details.php?id=' . $item_id);
                exit;
            } catch (Exception $e) {
                flash('message', ['type' => 'danger', 'message' => 'Error approving item: ' . $e->getMessage()]);
            }
            break;
            
        case 'reject':
            $reason = trim($_POST['reason'] ?? '');
            
            if (empty($reason)) {
                flash('message', ['type' => 'danger', 'message' => 'Rejection reason is required']);
            } else {
                try {
                    $update_sql = "UPDATE items 
                                  SET approval_status = 'rejected',
                                      status = 'rejected',
                                      rejection_reason = ?
                                  WHERE id = ?";
                    $db->execute($update_sql, [$reason, $item_id]);
                    
                    flash('message', ['type' => 'success', 'message' => 'Item rejected successfully']);
                    header('Location: item-details.php?id=' . $item_id);
                    exit;
                } catch (Exception $e) {
                    flash('message', ['type' => 'danger', 'message' => 'Error rejecting item: ' . $e->getMessage()]);
                }
            }
            break;
            
        case 'toggle_status':
            $new_status = $_POST['new_status'] === 'active' ? 'active' : 'inactive';
            
            try {
                $update_sql = "UPDATE items SET status = ? WHERE id = ?";
                $db->execute($update_sql, [$new_status, $item_id]);
                
                flash('message', ['type' => 'success', 'message' => 'Item status updated successfully']);
                header('Location: item-details.php?id=' . $item_id);
                exit;
            } catch (Exception $e) {
                flash('message', ['type' => 'danger', 'message' => 'Error updating item status: ' . $e->getMessage()]);
            }
            break;
    }
}

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

include '../templates/layouts/admin/head.php';
?>

<div class="main-content">

    <?php include '../templates/layouts/admin/header.php'; ?>
    
    <!-- Content -->
    <div class="content">
        
    <!-- Page Header -->
    <div style="padding: 30px; background: white; border-bottom: 1px solid #eee;">
        <div style="display: flex; justify-content: space-between; align-items: flex-start;">
            <div>
                <h1 style="font-size: 28px; font-weight: 700; color: var(--dark); margin-bottom: 5px;">
                    <?= Security::escapeOutput($item['title'] ?? 'Item Title Not Available') ?>
                </h1>
                <div style="display: flex; gap: 8px; font-size: 14px; color: #666;">
                    <a href="index.php" style="color: var(--primary); text-decoration: none;">Home</a>
                    <span>/</span>
                    <a href="items.php" style="color: var(--primary); text-decoration: none;">Items</a>
                    <span>/</span>
                    <span><?= Security::escapeOutput($item['title'] ?? 'Item') ?></span>
                </div>
            </div>
            
            <div style="display: flex; gap: 10px; align-items: center;">
                <?php if (($item['approval_status'] ?? '') === 'pending'): ?>
                    <span style="background: var(--warning); color: white; padding: 8px 16px; border-radius: 20px; font-size: 12px; font-weight: 600;">
                        Pending Approval
                    </span>
                <?php elseif (($item['approval_status'] ?? '') === 'approved'): ?>
                    <span style="background: var(--success); color: white; padding: 8px 16px; border-radius: 20px; font-size: 12px; font-weight: 600;">
                        Approved
                    </span>
                <?php else: ?>
                    <span style="background: var(--danger); color: white; padding: 8px 16px; border-radius: 20px; font-size: 12px; font-weight: 600;">
                        Rejected
                    </span>
                <?php endif; ?>
                
                <?php if (($item['status'] ?? '') === 'active'): ?>
                    <span style="background: var(--info); color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px;">
                        Active
                    </span>
                <?php else: ?>
                    <span style="background: var(--secondary); color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px;">
                        Inactive
                    </span>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Content -->
    <div style="padding: 30px;">
        
        <!-- Flash Messages -->
        <?php if ($flash_message): ?>
            <div class="alert alert-<?= $flash_message['type'] ?>">
                <?php 
                    if (is_array($flash_message['message'])) {
                        echo Security::escapeOutput(implode('<br>', $flash_message['message']));
                    } else {
                        echo Security::escapeOutput($flash_message['message']);
                    }
                ?>
            </div>
        <?php endif; ?>
        
        <!-- Item Overview Cards -->
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 20px; margin-bottom: 30px;">
            <!-- Item Details -->
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                    <i class="fas fa-info-circle"></i> Item Details
                </h3>
                
                <div style="margin-bottom: 15px;">
                    <label style="font-weight: 600; color: #666; font-size: 12px; text-transform: uppercase;">Title</label>
                    <div style="font-size: 16px; font-weight: 600;"><?= Security::escapeOutput($item['title'] ?? 'N/A') ?></div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="font-weight: 600; color: #666; font-size: 12px; text-transform: uppercase;">Category</label>
                    <div style="font-size: 14px;">
                        <?php if (!empty($item['category_icon'])): ?>
                            <i class="<?= Security::escapeOutput($item['category_icon']) ?>"></i>
                        <?php endif; ?>
                        <?= Security::escapeOutput($item['category_name'] ?? 'N/A') ?>
                    </div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="font-weight: 600; color: #666; font-size: 12px; text-transform: uppercase;">Price Per Day</label>
                    <div style="font-size: 16px; font-weight: 600; color: var(--success);">
                        <?= format_money($item['price_per_day'] ?? 0) ?>
                    </div>
                    <?php if (($item['security_deposit'] ?? 0) > 0): ?>
                        <small style="color: #666;">Security Deposit: <?= format_money($item['security_deposit'] ?? 0) ?></small>
                    <?php endif; ?>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="font-weight: 600; color: #666; font-size: 12px; text-transform: uppercase;">Location</label>
                    <div style="font-size: 14px;">
                        <?= Security::escapeOutput($item['location'] ?? '') ?><br>
                        <?= Security::escapeOutput(($item['city'] ?? '') . ', ' . ($item['state'] ?? '')) ?>
                    </div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="font-weight: 600; color: #666; font-size: 12px; text-transform: uppercase;">Condition</label>
                    <div style="font-size: 14px;"><?= ucfirst(str_replace('_', ' ', $item['condition_status'] ?? 'unknown')) ?></div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="font-weight: 600; color: #666; font-size: 12px; text-transform: uppercase;">Quantity</label>
                    <div style="font-size: 14px;">
                        Available: <?= $item['available_quantity'] ?? 0 ?> / Total: <?= $item['quantity'] ?? 0 ?>
                    </div>
                </div>
                
                <div>
                    <label style="font-weight: 600; color: #666; font-size: 12px; text-transform: uppercase;">Views</label>
                    <div style="font-size: 14px;"><?= number_format($item['views_count'] ?? 0) ?> views</div>
                </div>
            </div>
            
            <!-- Vendor Information -->
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                    <i class="fas fa-store"></i> Vendor Information
                </h3>
                
                <div style="margin-bottom: 15px;">
                    <label style="font-weight: 600; color: #666; font-size: 12px; text-transform: uppercase;">Business Name</label>
                    <div style="font-size: 16px; font-weight: 600;">
                        <a href="vendor-details.php?id=<?= $item['vendor_id'] ?? 0 ?>" style="color: var(--primary); text-decoration: none;">
                            <?= Security::escapeOutput($item['vendor_name'] ?? 'N/A') ?>
                        </a>
                    </div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="font-weight: 600; color: #666; font-size: 12px; text-transform: uppercase;">Email</label>
                    <div style="font-size: 14px;"><?= Security::escapeOutput($item['vendor_email'] ?? 'N/A') ?></div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="font-weight: 600; color: #666; font-size: 12px; text-transform: uppercase;">Phone</label>
                    <div style="font-size: 14px;"><?= format_phone($item['vendor_phone'] ?? '') ?></div>
                </div>
                
                <div style="margin-bottom: 15px;">
                    <label style="font-weight: 600; color: #666; font-size: 12px; text-transform: uppercase;">Wallet Balance</label>
                    <div style="font-size: 16px; font-weight: 600; color: var(--success);">
                        <?= format_money($item['vendor_balance'] ?? 0) ?>
                    </div>
                </div>
                
                <div>
                    <label style="font-weight: 600; color: #666; font-size: 12px; text-transform: uppercase;">Item Performance</label>
                    <div style="display: flex; gap: 10px; margin-top: 10px;">
                        <div style="text-align: center; padding: 8px; background: #f8f9fa; border-radius: 8px; flex: 1;">
                            <div style="font-size: 18px; font-weight: 700; color: var(--primary);"><?= $item['total_orders'] ?? 0 ?></div>
                            <div style="font-size: 11px; color: #666;">Total Orders</div>
                        </div>
                        <div style="text-align: center; padding: 8px; background: #f8f9fa; border-radius: 8px; flex: 1;">
                            <div style="font-size: 18px; font-weight: 700; color: var(--success);"><?= $item['completed_orders'] ?? 0 ?></div>
                            <div style="font-size: 11px; color: #666;">Completed</div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- Rating & Reviews -->
            <div style="background: white; border-radius: 12px; padding: 25px; box-shadow: 0 2px 10px rgba(0,0,0,0.05);">
                <h3 style="font-size: 18px; font-weight: 600; margin-bottom: 20px; color: var(--dark);">
                    <i class="fas fa-star"></i> Rating & Reviews
                </h3>
                
                <div style="margin-bottom: 20px; text-align: center;">
                    <div style="font-size: 48px; font-weight: 700; color: #ffc107; margin-bottom: 5px;">
                        <?= number_format($rating_stats['average_rating'] ?? 0, 1) ?>
                    </div>
                    <div style="margin-bottom: 10px;">
                        <?php for ($i = 1; $i <= 5; $i++): ?>
                            <i class="fas fa-star <?= $i <= ($rating_stats['average_rating'] ?? 0) ? 'text-warning' : 'text-light' ?>" style="color: #ffc107; font-size: 18px;"></i>
                        <?php endfor; ?>
                    </div>
                    <div style="color: #666; font-size: 14px;">Based on <?= $rating_stats['total_reviews'] ?? 0 ?> reviews</div>
                </div>
                
                <!-- Rating Breakdown -->
                <div style="margin-bottom: 20px;">
                    <?php
                    $ratings = [
                        5 => $rating_stats['five_star'] ?? 0,
                        4 => $rating_stats['four_star'] ?? 0,
                        3 => $rating_stats['three_star'] ?? 0,
                        2 => $rating_stats['two_star'] ?? 0,
                        1 => $rating_stats['one_star'] ?? 0
                    ];
                    
                    foreach ($ratings as $stars => $count):
                        $total_reviews = $rating_stats['total_reviews'] ?? 0;
                        $percentage = $total_reviews > 0 ? ($count / $total_reviews) * 100 : 0;
                    ?>
                        <div style="display: flex; align-items: center; margin-bottom: 8px;">
                            <span style="width: 30px; font-size: 12px; color: #666;"><?= $stars ?>★</span>
                            <div style="flex: 1; background: #f0f0f0; height: 6px; border-radius: 3px; margin: 0 10px;">
                                <div style="background: #ffc107; height: 100%; width: <?= $percentage ?>%; border-radius: 3px;"></div>
                            </div>
                            <span style="width: 30px; font-size: 12px; color: #666;"><?= $count ?></span>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        
        <!-- Tabs -->
        <div style="background: white; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); overflow: hidden;">
            <div style="border-bottom: 1px solid #eee;">
                <div style="display: flex; padding: 0;">
                    <button class="tab-button active" onclick="showTab('images')">
                        <i class="fas fa-images"></i> Images (<?= count($item_images) ?>)
                    </button>
                    <button class="tab-button" onclick="showTab('description')">
                        <i class="fas fa-align-left"></i> Description
                    </button>
                    <button class="tab-button" onclick="showTab('features')">
                        <i class="fas fa-list"></i> Features
                    </button>
                    <button class="tab-button" onclick="showTab('reviews')">
                        <i class="fas fa-comments"></i> Reviews (<?= count($reviews) ?>)
                    </button>
                    <button class="tab-button" onclick="showTab('orders')">
                        <i class="fas fa-shopping-cart"></i> Orders (<?= count($recent_orders) ?>)
                    </button>
                    <button class="tab-button" onclick="showTab('availability')">
                        <i class="fas fa-calendar"></i> Availability
                    </button>
                </div>
            </div>
            
            <!-- Images Tab -->
            <div id="images-tab" class="tab-content">
                <div style="padding: 25px;">
                    <h4 style="margin-bottom: 20px; color: var(--dark);">Item Images</h4>
                    
                    
                        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px;">
                            <!-- Main Image -->
                            <div style="position: relative;">
                                <img src="<?= upload('items/' . ($item['main_image'] ?? 'default.jpg')) ?>" 
                                     alt="Main Image"
                                     style="width: 100%; height: 200px; object-fit: cover; border-radius: 8px;">
                                <div style="position: absolute; top: 10px; left: 10px; background: var(--primary); color: white; padding: 4px 8px; border-radius: 12px; font-size: 12px; font-weight: 600;">
                                    Main
                                </div>
                            </div>
                            
                            <!-- Additional Images -->
                            <?php foreach ($item_images as $image): ?>
                                <div>
                                    <img src="<?= upload('items/' . ($image['image_path'])) ?>" 
                                         alt="Item Image"
                                         style="width: 100%; height: 200px; object-fit: cover; border-radius: 8px;">
                                </div>
                            <?php endforeach; ?>
                        </div>
                        
                </div>
            </div>
            
            <!-- Description Tab -->
            <div id="description-tab" class="tab-content" style="display: none;">
                <div style="padding: 25px;">
                    <div style="margin-bottom: 20px;">
                        <h4 style="margin-bottom: 10px; color: var(--dark);">Description</h4>
                        <p style="line-height: 1.6; color: #555;">
                            <?= nl2br(Security::escapeOutput($item['description'] ?? 'No description available')) ?>
                        </p>
                    </div>
                    
                    <?php if (!empty($item['rejection_reason'])): ?>
                        <div style="margin-bottom: 20px; padding: 15px; background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px;">
                            <h5 style="margin-bottom: 10px; color: #721c24;">
                                <i class="fas fa-exclamation-triangle"></i> Rejection Reason
                            </h5>
                            <p style="margin: 0; color: #721c24;"><?= Security::escapeOutput($item['rejection_reason']) ?></p>
                        </div>
                    <?php endif; ?>
                    
                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 20px;">
                        <div>
                            <h5 style="margin-bottom: 10px; color: var(--dark);">Created</h5>
                            <p style="margin: 0; color: #666;"><?= format_date($item['created_at'] ?? '') ?></p>
                        </div>
                        
                        <div>
                            <h5 style="margin-bottom: 10px; color: var(--dark);">Last Updated</h5>
                            <p style="margin: 0; color: #666;"><?= format_date($item['updated_at'] ?? '') ?></p>
                        </div>
                        
                        <?php if (!empty($item['approval_date'])): ?>
                            <div>
                                <h5 style="margin-bottom: 10px; color: var(--dark);">Approved</h5>
                                <p style="margin: 0; color: #666;"><?= format_date($item['approval_date']) ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            
            <!-- Features Tab -->
            <div id="features-tab" class="tab-content" style="display: none;">
                <div style="padding: 25px;">
                    <h4 style="margin-bottom: 20px; color: var(--dark);">Features & Terms</h4>
                    
                    <?php if (!empty($item['features'])): ?>
                        <div style="margin-bottom: 25px;">
                            <h5 style="margin-bottom: 15px; color: var(--dark);">Features</h5>
                            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px;">
                                <?= nl2br(Security::escapeOutput($item['features'])) ?>
                            </div>
                        </div>
                    <?php else: ?>
                        <div style="margin-bottom: 25px;">
                            <h5 style="margin-bottom: 15px; color: var(--dark);">Features</h5>
                            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; color: #666;">
                                No features specified
                            </div>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (!empty($item['terms_and_conditions'])): ?>
                        <div>
                            <h5 style="margin-bottom: 15px; color: var(--dark);">Terms & Conditions</h5>
                            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px;">
                                <?= nl2br(Security::escapeOutput($item['terms_and_conditions'])) ?>
                            </div>
                        </div>
                    <?php else: ?>
                        <div>
                            <h5 style="margin-bottom: 15px; color: var(--dark);">Terms & Conditions</h5>
                            <div style="background: #f8f9fa; padding: 20px; border-radius: 8px; color: #666;">
                                No terms and conditions specified
                            </div>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Reviews Tab -->
            <div id="reviews-tab" class="tab-content" style="display: none;">
                <div style="padding: 25px;">
                    <h4 style="margin-bottom: 20px; color: var(--dark);">Customer Reviews</h4>
                    
                    <?php if (empty($reviews)): ?>
                        <p style="color: #999; text-align: center; padding: 40px;">
                            <i class="fas fa-comments fa-3x mb-3"></i><br>
                            No reviews yet
                        </p>
                    <?php else: ?>
                        <?php foreach ($reviews as $review): ?>
                            <div style="border-bottom: 1px solid #f0f0f0; padding: 20px 0;">
                                <div style="display: flex; justify-content: between; align-items: flex-start; margin-bottom: 15px;">
                                    <div style="flex: 1;">
                                        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 5px;">
                                            <?php if (!empty($review['customer_avatar'])): ?>
                                                <img src="<?= upload($review['customer_avatar']) ?>" 
                                                     alt="<?= Security::escapeOutput($review['customer_name']) ?>"
                                                     style="width: 40px; height: 40px; border-radius: 50%; object-fit: cover;">
                                            <?php else: ?>
                                                <div style="width: 40px; height: 40px; border-radius: 50%; background: var(--primary); display: flex; align-items: center; justify-content: center; color: white; font-weight: 600;">
                                                    <?= strtoupper(substr($review['customer_name'], 0, 2)) ?>
                                                </div>
                                            <?php endif; ?>
                                            
                                            <div>
                                                <strong><?= Security::escapeOutput($review['customer_name']) ?></strong>
                                                <div style="color: #ffc107; margin-top: 2px;">
                                                    <?php for ($i = 1; $i <= 5; $i++): ?>
                                                        <i class="fas fa-star <?= $i <= $review['rating'] ? '' : 'text-light' ?>"></i>
                                                    <?php endfor; ?>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <small style="color: #666;"><?= format_date($review['created_at'], 'M d, Y h:i A') ?></small>
                                    </div>
                                    
                                    <span class="status-badge <?= $review['status'] === 'active' ? 'status-approved' : 'status-rejected' ?>">
                                        <?= ucfirst($review['status']) ?>
                                    </span>
                                </div>
                                
                                <p style="margin: 0; line-height: 1.6;">
                                    <?= Security::escapeOutput($review['review']) ?>
                                </p>
                                
                                <?php if (!empty($review['vendor_reply'])): ?>
                                    <div style="margin-top: 15px; padding: 15px; background: #f8f9fa; border-radius: 8px; border-left: 3px solid var(--primary);">
                                        <strong>Vendor Reply:</strong>
                                        <p style="margin: 5px 0 0 0; line-height: 1.5;">
                                            <?= Security::escapeOutput($review['vendor_reply']) ?>
                                        </p>
                                        <small style="color: #666;">
                                            <?= format_date($review['vendor_replied_at'], 'M d, Y h:i A') ?>
                                        </small>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Orders Tab -->
            <div id="orders-tab" class="tab-content" style="display: none;">
                <div style="padding: 25px;">
                    <h4 style="margin-bottom: 20px; color: var(--dark);">Recent Orders</h4>
                    
                    <?php if (empty($recent_orders)): ?>
                        <p style="color: #999; text-align: center; padding: 40px;">
                            <i class="fas fa-shopping-cart fa-3x mb-3"></i><br>
                            No orders yet
                        </p>
                    <?php else: ?>
                        <div style="overflow-x: auto;">
                            <table style="width: 100%; border-collapse: collapse;">
                                <thead>
                                    <tr style="background: #f8f9fa;">
                                        <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Order #</th>
                                        <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Customer</th>
                                        <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Period</th>
                                        <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Amount</th>
                                        <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Status</th>
                                        <th style="padding: 12px 15px; text-align: left; font-size: 13px; font-weight: 600; color: #666;">Date</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($recent_orders as $order): ?>
                                        <tr style="border-bottom: 1px solid #f0f0f0;">
                                            <td style="padding: 15px;">
                                                <strong><?= Security::escapeOutput($order['order_number']) ?></strong>
                                            </td>
                                            <td style="padding: 15px;">
                                                <?= Security::escapeOutput($order['customer_name']) ?>
                                            </td>
                                            <td style="padding: 15px;">
                                                <small>
                                                    <?= format_date($order['start_date'], 'M d') ?> - 
                                                    <?= format_date($order['end_date'], 'M d') ?>
                                                    <br>(<?= $order['rental_days'] ?> days)
                                                </small>
                                            </td>
                                            <td style="padding: 15px;">
                                                <strong><?= format_money($order['total_amount']) ?></strong>
                                            </td>
                                            <td style="padding: 15px;">
                                                <?php
                                                $status_class = '';
                                                switch($order['status']) {
                                                    case 'pending':
                                                        $status_class = 'status-pending';
                                                        break;
                                                    case 'confirmed':
                                                        $status_class = 'status-approved';
                                                        break;
                                                    case 'ongoing':
                                                        $status_class = 'status-info';
                                                        break;
                                                    case 'completed':
                                                        $status_class = 'status-success';
                                                        break;
                                                    case 'cancelled':
                                                        $status_class = 'status-rejected';
                                                        break;
                                                }
                                                ?>
                                                <span class="status-badge <?= $status_class ?>">
                                                    <?= ucfirst($order['status']) ?>
                                                </span>
                                            </td>
                                            <td style="padding: 15px;">
                                                <small><?= format_date($order['created_at'], 'M d, Y') ?></small>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <!-- Availability Tab -->
            <div id="availability-tab" class="tab-content" style="display: none;">
                <div style="padding: 25px;">
                    <h4 style="margin-bottom: 20px; color: var(--dark);">Availability Calendar</h4>
                    
                    <?php if (empty($availability)): ?>
                        <p style="color: #999; text-align: center; padding: 40px;">
                            <i class="fas fa-calendar fa-3x mb-3"></i><br>
                            No availability data
                        </p>
                    <?php else: ?>
                        <div style="display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 15px;">
                            <?php foreach ($availability as $day): ?>
                                <div style="padding: 15px; background: #f8f9fa; border-radius: 8px;">
                                    <div style="font-weight: 600; margin-bottom: 5px;">
                                        <?= format_date($day['date'], 'D, M d') ?>
                                    </div>
                                    <div>
                                        <?php
                                        $status_class = '';
                                        $status_text = '';
                                        switch($day['status']) {
                                            case 'available':
                                                $status_class = 'status-success';
                                                $status_text = 'Available';
                                                break;
                                            case 'booked':
                                                $status_class = 'status-info';
                                                $status_text = 'Booked';
                                                break;
                                            case 'blocked':
                                                $status_class = 'status-rejected';
                                                $status_text = 'Blocked';
                                                break;
                                        }
                                        ?>
                                        <span class="status-badge <?= $status_class ?>">
                                            <?= $status_text ?>
                                        </span>
                                        <?php if ($day['quantity_booked'] > 0): ?>
                                            <small style="color: #666; display: block; margin-top: 5px;">
                                                Qty: <?= $day['quantity_booked'] ?>
                                            </small>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <!-- Action Buttons -->
        <div style="margin-top: 30px; text-align: center;">
            <div style="display: flex; justify-content: center; gap: 15px; flex-wrap: wrap;">
                <?php if (($item['approval_status'] ?? '') === 'pending'): ?>
                    <button onclick="showApproveModal()" 
                            style="background: var(--success); color: white; border: none; padding: 12px 24px; border-radius: 6px; font-weight: 600; cursor: pointer;">
                        <i class="fas fa-check"></i> Approve Item
                    </button>
                    
                    <button onclick="showRejectModal()" 
                            style="background: var(--danger); color: white; border: none; padding: 12px 24px; border-radius: 6px; font-weight: 600; cursor: pointer;">
                        <i class="fas fa-times"></i> Reject Item
                    </button>
                <?php elseif (($item['approval_status'] ?? '') === 'approved'): ?>
                    <button onclick="toggleStatus('<?= ($item['status'] ?? 'inactive') === 'active' ? 'inactive' : 'active' ?>')" 
                            style="background: <?= ($item['status'] ?? 'inactive') === 'active' ? 'var(--warning)' : 'var(--success)' ?>; color: white; border: none; padding: 12px 24px; border-radius: 6px; font-weight: 600; cursor: pointer;">
                        <i class="fas fa-<?= ($item['status'] ?? 'inactive') === 'active' ? 'pause' : 'play' ?>"></i> 
                        <?= ($item['status'] ?? 'inactive') === 'active' ? 'Deactivate' : 'Activate' ?> Item
                    </button>
                <?php endif; ?>
                
                <a href="../vendor/item-details.php?id=<?= $item['id'] ?? 0 ?>" 
                   target="_blank"
                   style="background: var(--primary); color: white; border: none; padding: 12px 24px; border-radius: 6px; font-weight: 600; text-decoration: none; display: inline-flex; align-items: center; gap: 8px;">
                    <i class="fas fa-external-link-alt"></i> View Public Page
                </a>
                
                <button onclick="sendMessageToVendor(<?= $item['vendor_id'] ?? 0 ?>)" 
                        style="background: var(--info); color: white; border: none; padding: 12px 24px; border-radius: 6px; font-weight: 600; cursor: pointer;">
                    <i class="fas fa-envelope"></i> Message Vendor
                </button>
            </div>
        </div>
    </div>
</div>

<!-- Approve Modal -->
<div id="approveModal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999;">
    <div class="modal-content" style="background: white; margin: 100px auto; padding: 30px; border-radius: 12px; width: 90%; max-width: 400px;">
        <h3 style="margin-bottom: 20px; font-size: 20px; font-weight: 600;">Approve Item</h3>
        
        <form method="POST">
            <input type="hidden" name="action" value="approve">
            <input type="hidden" name="reason" value="Approved by admin">
            
            <p style="margin-bottom: 25px; line-height: 1.6;">Are you sure you want to approve this item? It will be made available for rental.</p>
            
            <div style="display: flex; gap: 15px; justify-content: flex-end;">
                <button type="button" onclick="closeModal()" class="btn btn-secondary">Cancel</button>
                <button type="submit" class="btn btn-success">Approve Item</button>
            </div>
        </form>
    </div>
</div>

<!-- Reject Modal -->
<div id="rejectModal" class="modal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 9999;">
    <div class="modal-content" style="background: white; margin: 100px auto; padding: 30px; border-radius: 12px; width: 90%; max-width: 400px;">
        <h3 style="margin-bottom: 20px; font-size: 20px; font-weight: 600;">Reject Item</h3>
        
        <form method="POST">
            <input type="hidden" name="action" value="reject">
            
            <div class="form-group" style="margin-bottom: 20px;">
                <label style="display: block; margin-bottom: 8px; font-weight: 600;">Reason *</label>
                <textarea name="reason" 
                          class="form-control" 
                          rows="4" 
                          placeholder="Please provide a reason for rejection"
                          required></textarea>
            </div>
            
            <div style="display: flex; gap: 15px; justify-content: flex-end;">
                <button type="button" onclick="closeModal()" class="btn btn-secondary">Cancel</button>
                <button type="submit" class="btn btn-danger">Reject Item</button>
            </div>
        </form>
    </div>
</div>

<!-- Toggle Status Form (hidden) -->
<form method="POST" id="toggleStatusForm" style="display: none;">
    <input type="hidden" name="action" value="toggle_status">
    <input type="hidden" name="new_status" id="newStatusInput">
</form>

<style>
.modal {
    animation: fadeIn 0.3s;
}

.modal-content {
    animation: slideIn 0.3s;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

@keyframes slideIn {
    from { transform: translateY(-50px); opacity: 0; }
    to { transform: translateY(0); opacity: 1; }
}

.tab-button {
    background: none;
    border: none;
    padding: 15px 20px;
    font-weight: 600;
    cursor: pointer;
    border-bottom: 3px solid transparent;
    color: #666;
    transition: all 0.3s;
    font-size: 14px;
}

.tab-button:hover {
    color: var(--primary);
    background: #f8f9fa;
}

.tab-button.active {
    color: var(--primary);
    border-bottom-color: var(--primary);
    background: #f8f9fa;
}

.status-approved {
    background: var(--success);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-pending {
    background: var(--warning);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-rejected {
    background: var(--danger);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-info {
    background: var(--info);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.status-success {
    background: var(--success);
    color: white;
    padding: 4px 12px;
    border-radius: 20px;
    font-size: 12px;
    font-weight: 600;
}

.text-light {
    color: #ccc !important;
}

.form-control {
    border: 1px solid #ddd;
    border-radius: 6px;
    padding: 10px 12px;
    font-size: 14px;
    transition: border-color 0.3s;
    width: 100%;
}

.form-control:focus {
    outline: none;
    border-color: var(--primary);
    box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.btn {
    border: none;
    border-radius: 6px;
    padding: 10px 20px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s;
    font-size: 14px;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #545b62;
}

.btn-success {
    background: var(--success);
    color: white;
}

.btn-danger {
    background: var(--danger);
    color: white;
}

.alert {
    padding: 15px 20px;
    border-radius: 8px;
    margin-bottom: 20px;
}

.alert-success {
    background: #d4edda;
    color: #155724;
    border: 1px solid #c3e6cb;
}

.alert-danger {
    background: #f8d7da;
    color: #721c24;
    border: 1px solid #f5c6cb;
}
</style>

<script>
function showTab(tabName) {
    // Hide all tabs
    const tabs = ['description', 'images', 'features', 'reviews', 'orders', 'availability'];
    tabs.forEach(tab => {
        const tabElement = document.getElementById(tab + '-tab');
        const buttonElement = document.querySelector(`[onclick="showTab('${tab}')"]`);
        if (tabElement) tabElement.style.display = 'none';
        if (buttonElement) buttonElement.classList.remove('active');
    });
    
    // Show selected tab
    const selectedTab = document.getElementById(tabName + '-tab');
    const selectedButton = document.querySelector(`[onclick="showTab('${tabName}')"]`);
    if (selectedTab) selectedTab.style.display = 'block';
    if (selectedButton) selectedButton.classList.add('active');
}

function showApproveModal() {
    document.getElementById('approveModal').style.display = 'block';
}

function showRejectModal() {
    document.getElementById('rejectModal').style.display = 'block';
}

function closeModal() {
    document.getElementById('approveModal').style.display = 'none';
    document.getElementById('rejectModal').style.display = 'none';
}

function toggleStatus(newStatus) {
    const action = newStatus === 'active' ? 'activate' : 'deactivate';
    if (confirm(`Are you sure you want to ${action} this item?`)) {
        document.getElementById('newStatusInput').value = newStatus;
        document.getElementById('toggleStatusForm').submit();
    }
}

function sendMessageToVendor(vendorId) {
    // Implementation for sending message to vendor
    alert('Message feature coming soon!');
}

// Close modals when clicking outside
window.onclick = function(event) {
    const approveModal = document.getElementById('approveModal');
    const rejectModal = document.getElementById('rejectModal');
    
    if (event.target === approveModal) {
        closeModal();
    }
    if (event.target === rejectModal) {
        closeModal();
    }
}

// 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>

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