<?php
/**
 * ADMIN ITEMS MANAGEMENT PAGE
 * File: admin/items.php
 * Manage all rental items, approve/reject pending items, view statistics
 */

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

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

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

// 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 = ADMIN_ITEMS_PER_PAGE;

// Build WHERE clause
$where_conditions = [];
$params = [];

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 ? OR v.business_name LIKE ?)";
    $search_term = "%$search%";
    $params[] = $search_term;
    $params[] = $search_term;
    $params[] = $search_term;
}

$where_clause = !empty($where_conditions) ? 'WHERE ' . implode(' AND ', $where_conditions) : '';

// Get total count
$db = Database::getInstance();
$count_sql = "SELECT COUNT(*) as total 
              FROM items i 
              LEFT JOIN vendors v ON i.vendor_id = v.id 
              $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.*, 
        v.business_name as vendor_name,
        c.name as category_name,
        u.email as vendor_email,
        (SELECT COUNT(*) FROM orders WHERE item_id = i.id) as total_orders
        FROM items i
        LEFT JOIN vendors v ON i.vendor_id = v.id
        LEFT JOIN users u ON v.user_id = u.id
        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->count(),
    'pending' => $item->countByStatus('pending'),
    'approved' => $item->countByStatus('approved'),
    'rejected' => $item->countByStatus('rejected')
];

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

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

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

<div class="main-content">

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

    <div class="page-header">
        <div class="header-left">
            <h1><i class="fas fa-box"></i> Items Management</h1>
            <p class="text-muted">Manage all rental items on the platform</p>
        </div>
    </div>

    <!-- Content -->
    <div class="content">

    <!-- 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-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-success">
                <i class="fas fa-check-circle"></i>
            </div>
            <div class="stat-details">
                <h3><?= number_format($stats['approved']) ?></h3>
                <p>Approved Items</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 Items</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">
                            <option value="all" <?= $status_filter === 'all' ? 'selected' : '' ?>>All Status</option>
                            <option value="pending" <?= $status_filter === 'pending' ? 'selected' : '' ?>>Pending</option>
                            <option value="approved" <?= $status_filter === 'approved' ? 'selected' : '' ?>>Approved</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">
                            <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-4">
                        <label class="form-label">Search</label>
                        <input type="text" name="search" class="form-control" 
                               placeholder="Search items, vendors..." 
                               value="<?= esc($search) ?>">
                    </div>
                    
                    <div class="col-md-2">
                        <label class="form-label">&nbsp;</label>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary flex-fill">
                                <i class="fas fa-search"></i> Filter
                            </button>
                            <a href="items.php" class="btn btn-secondary">
                                <i class="fas fa-redo"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <!-- Items Table -->
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">
                <i class="fas fa-list"></i> Items List
                <span class="badge bg-secondary"><?= number_format($total_items) ?> items</span>
            </h5>
        </div>
        <div class="card-body p-0">
            <?php if (empty($items)): ?>
                <div class="empty-state py-5">
                    <i class="fas fa-box fa-3x text-muted mb-3"></i>
                    <p class="text-muted">No items found</p>
                </div>
            <?php else: ?>
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead>
                            <tr>
                                <th width="80">Image</th>
                                <th>Item Details</th>
                                <th>Vendor</th>
                                <th>Category</th>
                                <th width="120">Price/Day</th>
                                <th width="100">Status</th>
                                <th width="100">Orders</th>
                                <th width="100">Rating</th>
                                <th width="150">Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($items as $item_data): ?>
                                <tr>
                                    <td>
                                        <img src="<?= upload('items/' . $item_data['main_image']) ?>"  
                                             alt="<?= esc($item_data['title']) ?>"
                                             class="item-thumbnail">
                                    </td>
                                    <td>
                                        <strong><?= esc($item_data['title']) ?></strong><br>
                                        <small class="text-muted">
                                            <i class="fas fa-map-marker-alt"></i> 
                                            <?= esc($item_data['city']) ?>, <?= esc($item_data['state']) ?>
                                        </small><br>
                                        <small class="text-muted">
                                            Qty: <?= $item_data['quantity'] ?> | 
                                            Available: <?= $item_data['available_quantity'] ?>
                                        </small>
                                    </td>
                                    <td>
                                        <strong><?= esc($item_data['vendor_name']) ?></strong><br>
                                        <small class="text-muted"><?= esc($item_data['vendor_email']) ?></small>
                                    </td>
                                    <td><?= esc($item_data['category_name']) ?></td>
                                    <td>
                                        <strong><?= format_money($item_data['price_per_day']) ?></strong><br>
                                        <?php if ($item_data['security_deposit'] > 0): ?>
                                            <small class="text-muted">
                                                Deposit: <?= format_money($item_data['security_deposit']) ?>
                                            </small>
                                        <?php endif; ?>
                                    </td>
                                    <td><?= format_status_badge($item_data['approval_status']) ?></td>
                                    <td class="text-center">
                                        <span class="badge bg-info"><?= $item_data['total_orders'] ?></span>
                                    </td>
                                    <td>
                                        <?= format_rating($item_data['rating_average']) ?><br>
                                        <small class="text-muted">(<?= $item_data['rating_count'] ?> reviews)</small>
                                    </td>
                                    <td>
                                        <div class="btn-group-vertical btn-group-sm">
                                            <a href="item-details.php?id=<?= $item_data['id'] ?>" 
                                               class="btn btn-sm btn-info">
                                                <i class="fas fa-eye"></i> View
                                            </a>
                                            
                                            <?php if ($item_data['approval_status'] === 'pending'): ?>
                                                <a href="item-approve.php?id=<?= $item_data['id'] ?>" 
                                                   class="btn btn-sm btn-success">
                                                    <i class="fas fa-check"></i> Approve
                                                </a>
                                                <a href="item-reject.php?id=<?= $item_data['id'] ?>" 
                                                   class="btn btn-sm btn-danger">
                                                    <i class="fas fa-times"></i> Reject
                                                </a>
                                            <?php elseif ($item_data['approval_status'] === 'approved'): ?>
                                                <a href="item-reject.php?id=<?= $item_data['id'] ?>" 
                                                   class="btn btn-sm btn-warning"
                                                   onclick="return confirm('Reject this approved item?')">
                                                    <i class="fas fa-ban"></i> Reject
                                                </a>
                                            <?php else: ?>
                                                <a href="item-approve.php?id=<?= $item_data['id'] ?>" 
                                                   class="btn btn-sm btn-success">
                                                    <i class="fas fa-check"></i> Approve
                                                </a>
                                            <?php endif; ?>
                                        </div>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <?php if ($total_pages > 1): ?>
                    <div class="card-footer">
                        <?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>
    </div>
</div>

<style>
.item-thumbnail {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 8px;
}

.btn-group-vertical .btn {
    margin-bottom: 2px;
}
</style>

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