<?php
/**
 * VENDOR ITEMS LISTING PAGE
 * File: modules/vendor/items.php
 * View and manage all vendor's rental items
 */

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

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

// Initialize models
$vendor = new Vendor();
$item = new Item();
$category = new Category();

// 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('/modules/vendor/profile.php');
}

// Get filter parameters
$status_filter = $_GET['status'] ?? 'all';
$category_filter = $_GET['category'] ?? 'all';
$search = $_GET['search'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 12;

// Build WHERE clause
$where_conditions = ["i.vendor_id = ?"];
$params = [$vendor_data['id']];

if ($status_filter !== 'all') {
    $where_conditions[] = "i.approval_status = ?";
    $params[] = $status_filter;
}

if ($category_filter !== 'all') {
    $where_conditions[] = "i.category_id = ?";
    $params[] = $category_filter;
}

if (!empty($search)) {
    $where_conditions[] = "(i.title LIKE ? OR i.description LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
}

$where_clause = 'WHERE ' . implode(' AND ', $where_conditions);

// Get total count
$db = Database::getInstance();
$count_sql = "SELECT COUNT(*) as total FROM items i $where_clause";
$count_result = $db->fetch($count_sql, $params);
$total_items = $count_result['total'];
$total_pages = ceil($total_items / $per_page);
$offset = ($page - 1) * $per_page;

// Get items
$sql = "SELECT i.*, 
        c.name as category_name,
        (SELECT COUNT(*) FROM orders WHERE item_id = i.id) as total_orders,
        (SELECT COUNT(*) FROM orders WHERE item_id = i.id AND status = 'ongoing') as active_orders
        FROM items i
        LEFT JOIN categories c ON i.category_id = c.id
        $where_clause
        ORDER BY i.created_at DESC
        LIMIT ? OFFSET ?";

$params[] = $per_page;
$params[] = $offset;
$items = $db->fetchAll($sql, $params);

// Get statistics
$stats = [
    'total' => $item->countByVendor($vendor_data['id']),
    'pending' => $item->countByVendorAndStatus($vendor_data['id'], 'pending'),
    'approved' => $item->countByVendorAndStatus($vendor_data['id'], 'approved'),
    'rejected' => $item->countByVendorAndStatus($vendor_data['id'], 'rejected')
];

// Get categories
$categories = $category->getActive();

// Page variables
$page_title = "My Items";
$active_menu = "items";

// Include header
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> My Items</h1>
            <p class="text-muted">Manage your rental inventory</p>
        </div>
        <div class="header-right">
            <a href="item-form.php" class="btn btn-primary">
                <i class="fas fa-plus"></i> Add New Item
            </a>
        </div>
    </div>

    <!-- Statistics Cards -->
    <div class="stats-grid mb-4">
        <div class="stat-card">
            <div class="stat-icon bg-primary">
                <i class="fas fa-box"></i>
            </div>
            <div class="stat-details">
                <h3><?= number_format($stats['total']) ?></h3>
                <p>Total Items</p>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon bg-success">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-details">
                <h3><?= number_format($stats['approved']) ?></h3>
                <p>Live Items</p>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon bg-warning">
                <i class="fas fa-clock"></i>
            </div>
            <div class="stat-details">
                <h3><?= number_format($stats['pending']) ?></h3>
                <p>Pending Approval</p>
            </div>
        </div>
        
        <div class="stat-card">
            <div class="stat-icon bg-danger">
                <i class="fas fa-times-circle"></i>
            </div>
            <div class="stat-details">
                <h3><?= number_format($stats['rejected']) ?></h3>
                <p>Rejected</p>
            </div>
        </div>
    </div>

    <!-- Filters -->
    <div class="card mb-4">
        <div class="card-body">
            <form method="GET" class="filter-form">
                <div class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">Status</label>
                        <select name="status" class="form-control" onchange="this.form.submit()">
                            <option value="all" <?= $status_filter === 'all' ? 'selected' : '' ?>>All Status</option>
                            <option value="approved" <?= $status_filter === 'approved' ? 'selected' : '' ?>>Approved</option>
                            <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Pending</option>
                            <option value="rejected" <?= $status_filter === 'rejected' ? 'selected' : '' ?>>Rejected</option>
                        </select>
                    </div>
                    
                    <div class="col-md-3">
                        <label class="form-label">Category</label>
                        <select name="category" class="form-control" onchange="this.form.submit()">
                            <option value="all">All Categories</option>
                            <?php foreach ($categories as $cat): ?>
                                <option value="<?= $cat['id'] ?>" <?= $category_filter == $cat['id'] ? 'selected' : '' ?>>
                                    <?= esc($cat['name']) ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    
                    <div class="col-md-5">
                        <label class="form-label">Search</label>
                        <input type="text" name="search" class="form-control" 
                               placeholder="Search items..." 
                               value="<?= esc($search) ?>">
                    </div>
                    
                    <div class="col-md-1">
                        <label class="form-label">&nbsp;</label>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-search"></i>
                            </button>
                            <a href="items.php" class="btn btn-secondary">
                                <i class="fas fa-redo"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Items Grid -->
    <?php if (empty($items)): ?>
        <div class="card">
            <div class="card-body text-center py-5">
                <i class="fas fa-box-open fa-4x text-muted mb-4"></i>
                <h3>No Items Yet</h3>
                <p class="text-muted mb-4">Start listing your items to begin earning!</p>
                <a href="item-form.php" class="btn btn-primary btn-lg">
                    <i class="fas fa-plus"></i> Add Your First Item
                </a>
            </div>
        </div>
    <?php else: ?>
        <div class="row">
            <?php foreach ($items as $item_data): ?>
                <div class="col-lg-3 col-md-4 col-sm-6 mb-4">
                    <div class="item-card">
                        <div class="item-image">
                            <img src="<?= upload('items/' . $item_data['main_image']) ?>" 
                                 alt="<?= esc($item_data['title']) ?>">
                            
                            <!-- Status Badge -->
                            <div class="item-status">
                                <?= format_status_badge($item_data['approval_status']) ?>
                            </div>
                            
                            <!-- Active Orders Badge -->
                            <?php if ($item_data['active_orders'] > 0): ?>
                                <div class="item-active-badge">
                                    <span class="badge bg-info">
                                        <?= $item_data['active_orders'] ?> active rental<?= $item_data['active_orders'] > 1 ? 's' : '' ?>
                                    </span>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <div class="item-body">
                            <h5 class="item-title"><?= esc($item_data['title']) ?></h5>
                            <p class="item-category text-muted">
                                <i class="fas fa-tag"></i> <?= esc($item_data['category_name']) ?>
                            </p>
                            
                            <div class="item-stats mb-3">
                                <div class="d-flex justify-content-between text-muted small">
                                    <span><i class="fas fa-eye"></i> <?= number_format($item_data['views_count']) ?> views</span>
                                    <span><i class="fas fa-shopping-bag"></i> <?= $item_data['total_orders'] ?> orders</span>
                                </div>
                            </div>
                            
                            <div class="item-price mb-3">
                                <strong class="text-primary"><?= format_money($item_data['price_per_day']) ?></strong>
                                <span class="text-muted">/day</span>
                            </div>
                            
                            <div class="item-availability mb-3">
                                <small class="text-muted">
                                    Available: <?= $item_data['available_quantity'] ?> / <?= $item_data['quantity'] ?>
                                </small>
                            </div>
                            
                            <?php if ($item_data['approval_status'] === 'rejected' && !empty($item_data['rejection_reason'])): ?>
                                <div class="alert alert-danger py-2 small mb-3">
                                    <strong>Rejection Reason:</strong><br>
                                    <?= str_limit(esc($item_data['rejection_reason']), 80) ?>
                                </div>
                            <?php endif; ?>
                            
                            <div class="item-actions">
                                <a href="item-form.php?id=<?= $item_data['id'] ?>" class="btn btn-sm btn-primary w-100 mb-2">
                                    <i class="fas fa-edit"></i> Edit
                                </a>
                                
                                <div class="btn-group w-100 mb-2">
                                    <a href="item-details.php?id=<?= $item_data['id'] ?>" class="btn btn-sm btn-outline-info">
                                        <i class="fas fa-eye"></i> View
                                    </a>
                                    <a href="calendar.php?item_id=<?= $item_data['id'] ?>" class="btn btn-sm btn-outline-secondary">
                                        <i class="fas fa-calendar"></i> Calendar
                                    </a>
                                </div>
                                
                                <a href="delete-item.php?id=<?= $item_data['id'] ?>" 
                                   class="btn btn-sm btn-outline-danger w-100"
                                   onclick="return confirm('Are you sure you want to delete this item?')">
                                    <i class="fas fa-trash"></i> Delete
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <div class="d-flex justify-content-center mt-4">
                <?php 
                $pagination_params = array_filter([
                    'status' => $status_filter !== 'all' ? $status_filter : null,
                    'category' => $category_filter !== 'all' ? $category_filter : null,
                    'search' => !empty($search) ? $search : null
                ]);
                echo render_pagination($page, $total_pages, 'items.php', $pagination_params); 
                ?>
            </div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<style>
.item-card {
    background: white;
    border-radius: 10px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    transition: transform 0.3s, box-shadow 0.3s;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.item-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 20px rgba(0,0,0,0.15);
}

.item-image {
    position: relative;
    width: 100%;
    height: 200px;
    overflow: hidden;
}

.item-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.item-status {
    position: absolute;
    top: 10px;
    right: 10px;
}

.item-active-badge {
    position: absolute;
    top: 10px;
    left: 10px;
}

.item-body {
    padding: 15px;
    flex: 1;
    display: flex;
    flex-direction: column;
}

.item-title {
    font-size: 1.1rem;
    font-weight: 600;
    margin-bottom: 8px;
    min-height: 2.5rem;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}

.item-category {
    font-size: 0.85rem;
    margin-bottom: 10px;
}

.item-stats {
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
    padding: 8px 0;
}

.item-price {
    font-size: 1.2rem;
}

.item-actions {
    margin-top: auto;
}
</style>

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