<?php
session_start();
require_once "../config/db.php";
require_once "../config/site-config.php";

if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit();
}

// Current page for pagination
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 20;
$offset = ($page - 1) * $limit;

// Search and filter
$search = isset($_GET['search']) ? mysqli_real_escape_string($conn, $_GET['search']) : '';
$category = isset($_GET['category']) ? (int)$_GET['category'] : 0;
$status = isset($_GET['status']) ? mysqli_real_escape_string($conn, $_GET['status']) : '';
$featured = isset($_GET['featured']) ? (int)$_GET['featured'] : '';

// Build WHERE clause
$where = "WHERE (p.is_deleted = 0 OR p.is_deleted IS NULL)";

if (!empty($search)) {
    $where .= " AND (p.name LIKE '%$search%' OR p.description LIKE '%$search%')";
}

if ($category > 0) {
    $where .= " AND p.category_id = $category";
}

if (!empty($status)) {
    $where .= " AND p.status = '$status'";
}

if ($featured === 1) {
    $where .= " AND p.featured = 1";
}

// Get total count for pagination
$count_result = mysqli_fetch_assoc(mysqli_query($conn, 
    "SELECT COUNT(*) as total FROM products p $where"
));
$total_products = $count_result['total'];
$total_pages = ceil($total_products / $limit);

// Get products with category name
$products = mysqli_query($conn,
    "SELECT p.*, c.category_name
     FROM products p
     LEFT JOIN categories c ON p.category_id = c.id
     $where
     ORDER BY p.created_at DESC
     LIMIT $limit OFFSET $offset"
);

// Get categories for filter dropdown
$categories = mysqli_query($conn, "SELECT id, category_name FROM categories ORDER BY category_name");

// Handle bulk actions
if (isset($_POST['bulk_action'])) {
    $action = $_POST['bulk_action'];
    $product_ids = isset($_POST['product_ids']) ? $_POST['product_ids'] : [];
    
    if (!empty($product_ids)) {
        $ids = implode(',', array_map('intval', $product_ids));
        
        switch ($action) {
            case 'delete':
                if(!empty($product_ids)) {
                    $delete_ids = implode(',', array_map('intval', $product_ids));
                    mysqli_query($conn, "UPDATE products SET is_deleted = 1 WHERE id IN ($delete_ids)");
                    $message = count($product_ids) . " products removed successfully!";
                }
                break;
                
            case 'activate':
                mysqli_query($conn, "UPDATE products SET status = 'active' WHERE id IN ($ids)");
                $message = "Selected products activated successfully!";
                break;
                
            case 'deactivate':
                mysqli_query($conn, "UPDATE products SET status = 'inactive' WHERE id IN ($ids)");
                $message = "Selected products deactivated successfully!";
                break;
                
            case 'feature':
                mysqli_query($conn, "UPDATE products SET featured = 1 WHERE id IN ($ids)");
                $message = "Selected products marked as featured!";
                break;
                
            case 'unfeature':
                mysqli_query($conn, "UPDATE products SET featured = 0 WHERE id IN ($ids)");
                $message = "Selected products unmarked as featured!";
                break;
        }
        
        $_SESSION['flash_message'] = $message;
        header("Location: products.php");
        exit();
    }
}

// Handle single product actions
if (isset($_GET['action'])) {
    $action = $_GET['action'];
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    
    if ($id > 0) {
        switch ($action) {
            case 'delete':
                mysqli_query($conn, "UPDATE products SET is_deleted = 1 WHERE id = $id");
                $_SESSION['flash_message'] = "Product removed successfully!";
                break;
                
            case 'activate':
                mysqli_query($conn, "UPDATE products SET status = 'active' WHERE id = $id");
                $_SESSION['flash_message'] = "Product activated successfully!";
                break;
                
            case 'deactivate':
                mysqli_query($conn, "UPDATE products SET status = 'inactive' WHERE id = $id");
                $_SESSION['flash_message'] = "Product deactivated successfully!";
                break;
                
            case 'feature':
                mysqli_query($conn, "UPDATE products SET featured = 1 WHERE id = $id");
                $_SESSION['flash_message'] = "Product marked as featured!";
                break;
                
            case 'unfeature':
                mysqli_query($conn, "UPDATE products SET featured = 0 WHERE id = $id");
                $_SESSION['flash_message'] = "Product unmarked as featured!";
                break;
        }
        
        header("Location: products.php");
        exit();
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Manage Products - <?php echo getSiteName(); ?> Admin</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        :root {
            --primary-orange: #ff6b35;
            --dark-blue: #2c3e50;
        }
        
        .sidebar {
            background: linear-gradient(180deg, var(--dark-blue) 0%, #1a252f 100%);
            min-height: 100vh;
            color: white;
            padding: 0;
            position: fixed;
            width: 250px;
        }
        .sidebar-header {
            padding: 30px 20px;
            background: rgba(255,255,255,0.1);
            text-align: center;
        }
        .sidebar-header i {
            font-size: 4rem;
            margin-bottom: 15px;
            color: var(--primary-orange);
        }
        .sidebar-menu {
            padding: 20px 0;
        }
        .sidebar-menu a {
            color: white;
            padding: 12px 25px;
            display: block;
            text-decoration: none;
            transition: all 0.3s;
            border-left: 3px solid transparent;
        }
        .sidebar-menu a:hover {
            background: rgba(255,255,255,0.1);
            border-left-color: var(--primary-orange);
            padding-left: 30px;
        }
        .sidebar-menu a.active {
            background: rgba(255,107,53,0.2);
            border-left-color: var(--primary-orange);
        }
        .sidebar-menu i {
            width: 25px;
            margin-right: 10px;
        }
        
        .main-content {
            margin-left: 200px;
            padding: 30px;
            background: #f8f9fa;
            min-height: 100vh;
        }
        
        .product-img {
            width: 60px;
            height: 60px;
            border-radius: 8px;
            object-fit: cover;
        }
        
        .status-badge {
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }
        
        .status-active { background: #d4edda; color: #155724; }
        .status-inactive { background: #f8d7da; color: #721c24; }
        
        .featured-badge {
            background: #ff6b35;
            color: white;
            padding: 3px 10px;
            border-radius: 5px;
            font-size: 0.7rem;
        }
        
        .btn-orange {
            background: linear-gradient(45deg, var(--primary-orange), #ff8e53);
            border: none;
            color: white;
            padding: 8px 20px;
            border-radius: 20px;
            font-weight: 600;
        }
        
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                position: relative;
                min-height: auto;
            }
            .main-content {
                margin-left: 0;
            }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <?php include "includes/sidebar.php"; ?>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Header -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 style="color: var(--dark-blue);">
                    <i class="fas fa-box me-2"></i>Manage Products
                </h1>
                <p class="text-muted mb-0">Total <?php echo number_format($total_products); ?> products</p>
            </div>
            <div>
                <a href="add-product.php" class="btn btn-orange">
                    <i class="fas fa-plus me-2"></i>Add New Product
                </a>
            </div>
        </div>

        <!-- Flash Message -->
        <?php if(isset($_SESSION['flash_message'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="fas fa-check-circle me-2"></i>
                <?php echo $_SESSION['flash_message']; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['flash_message']); ?>
        <?php endif; ?>

        <?php if(isset($_SESSION['flash_error'])): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo $_SESSION['flash_error']; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
            <?php unset($_SESSION['flash_error']); ?>
        <?php endif; ?>

        <!-- Filters -->
        <div class="card mb-4">
            <div class="card-body">
                <form method="GET" class="row g-3">
                    <div class="col-md-3">
                        <input type="text" 
                               name="search" 
                               class="form-control" 
                               placeholder="Search products..."
                               value="<?php echo htmlspecialchars($search); ?>">
                    </div>
                    <div class="col-md-2">
                        <select name="category" class="form-select">
                            <option value="">All Categories</option>
                            <?php while($cat = mysqli_fetch_assoc($categories)): ?>
                                <option value="<?php echo $cat['id']; ?>" 
                                    <?php echo $category == $cat['id'] ? 'selected' : ''; ?>>
                                    <?php echo htmlspecialchars($cat['category_name']); ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select name="status" class="form-select">
                            <option value="">All Status</option>
                            <option value="active" <?php echo $status == 'active' ? 'selected' : ''; ?>>Active</option>
                            <option value="inactive" <?php echo $status == 'inactive' ? 'selected' : ''; ?>>Inactive</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select name="featured" class="form-select">
                            <option value="">All</option>
                            <option value="1" <?php echo $featured === 1 ? 'selected' : ''; ?>>Featured Only</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <button type="submit" class="btn btn-primary me-2">
                            <i class="fas fa-filter me-2"></i>Filter
                        </button>
                        <a href="products.php" class="btn btn-outline-secondary">
                            <i class="fas fa-redo me-2"></i>Reset
                        </a>
                    </div>
                </form>
            </div>
        </div>

        <!-- Bulk Actions -->
        <form method="POST" id="bulkForm">
            <div class="d-flex justify-content-between align-items-center mb-3">
                <div>
                    <select name="bulk_action" class="form-select d-inline-block w-auto">
                        <option value="">Bulk Actions</option>
                        <option value="activate">Activate</option>
                        <option value="deactivate">Deactivate</option>
                        <option value="feature">Mark as Featured</option>
                        <option value="unfeature">Unmark Featured</option>
                        <option value="delete">Delete</option>
                    </select>
                    <button type="button" class="btn btn-outline-primary btn-sm ms-2" onclick="selectAll()">
                        <i class="fas fa-check-square me-1"></i>Select All
                    </button>
                    <button type="button" class="btn btn-outline-secondary btn-sm ms-1" onclick="deselectAll()">
                        <i class="fas fa-square me-1"></i>Deselect All
                    </button>
                    <button type="submit" class="btn btn-success btn-sm ms-1" onclick="return confirmBulkAction()">
                        <i class="fas fa-play me-1"></i>Apply
                    </button>
                </div>
                <div class="text-muted">
                    Showing <?php echo number_format(min($limit, $total_products - $offset)); ?> of <?php echo number_format($total_products); ?> products
                </div>
            </div>

            <!-- Products Table -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th width="50">
                                        <input type="checkbox" id="selectAll" onclick="toggleSelectAll(this)">
                                    </th>
                                    <th>Product</th>
                                    <th>Category</th>
                                    <th>Price</th>
                                    <th>Stock</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if(mysqli_num_rows($products) > 0): ?>
                                    <?php while($product = mysqli_fetch_assoc($products)): ?>
                                    <tr>
                                        <td>
                                            <input type="checkbox" name="product_ids[]" value="<?php echo $product['id']; ?>" class="product-checkbox">
                                        </td>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                   <?php
                                                   // Helper to get first image
                                                   $imgStr = $product['images'] ?? '';
                                                   $decoded = json_decode($imgStr, true);
                                                   $imgList = is_array($decoded) ? $decoded : [$imgStr];
                                                   $thumb = !empty($imgList[0]) ? $imgList[0] : '';
                                                   
                                                   $admin_img_src = !empty($thumb) ? '../assets/images/products/' . $thumb : '../assets/images/products/placeholder.jpg';
                                                   ?>
                                                   <img src="<?php echo $admin_img_src; ?>" 
                                                       class="product-img me-3" 
                                                       alt="<?php echo htmlspecialchars($product['name']); ?>"
                                                       onerror="this.src='../assets/images/products/placeholder.jpg'">
                                                <div>
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($product['name']); ?></h6>
                                                    <small class="text-muted">ID: <?php echo $product['id']; ?></small>
                                                    <?php if($product['featured']): ?>
                                                        <span class="featured-badge ms-2">Featured</span>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        </td>
                                        <td><?php echo htmlspecialchars($product['category_name'] ?? 'Uncategorized'); ?></td>
                                        <td>
                                            <div class="fw-bold"><?php echo formatPrice($product['price']); ?> (Rental)</div>
                                            <div class="small text-muted">
                                                MRP: <?php echo formatPrice($product['market_price'] ?? 0); ?>
                                            </div>
                                            <?php if($product['discount_percent'] > 0 || $product['original_price'] > 0): ?>
                                                <small class="text-muted">
                                                    <?php if($product['original_price'] > 0): ?>
                                                        <del><?php echo formatPrice($product['original_price']); ?></del>
                                                    <?php endif; ?>
                                                    <?php if($product['discount_percent'] > 0): ?>
                                                        <span class="text-danger ms-2">-<?php echo $product['discount_percent']; ?>%</span>
                                                    <?php endif; ?>
                                                </small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <div class="fw-bold <?php echo $product['stock'] <= 5 ? 'text-danger' : 'text-success'; ?>">
                                                <?php echo $product['stock']; ?>
                                            </div>
                                            <?php if($product['stock'] <= 5): ?>
                                                <small class="text-danger">Low Stock</small>
                                            <?php endif; ?>
                                        </td>
                                        <td>
                                            <span class="status-badge status-<?php echo $product['status'] ?? 'active'; ?>">
                                                <?php echo ucfirst($product['status'] ?? 'active'); ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm">
                                                <a href="../product-details.php?id=<?php echo $product['id']; ?>" 
                                                   class="btn btn-outline-primary" target="_blank" title="View">
                                                    <i class="fas fa-eye"></i>
                                                </a>
                                                <a href="edit-product.php?id=<?php echo $product['id']; ?>" 
                                                   class="btn btn-outline-warning" title="Edit">
                                                    <i class="fas fa-edit"></i>
                                                </a>
                                                <div class="btn-group btn-group-sm">
                                                    <button type="button" class="btn btn-outline-secondary dropdown-toggle" 
                                                            data-bs-toggle="dropdown" title="More">
                                                        <i class="fas fa-ellipsis-v"></i>
                                                    </button>
                                                    <ul class="dropdown-menu">
                                                        <?php if(($product['status'] ?? '') == 'active'): ?>
                                                            <li><a class="dropdown-item" href="?action=deactivate&id=<?php echo $product['id']; ?>" onclick="return confirm('Deactivate this product?')">
                                                                <i class="fas fa-times-circle me-2"></i>Deactivate
                                                            </a></li>
                                                        <?php else: ?>
                                                            <li><a class="dropdown-item" href="?action=activate&id=<?php echo $product['id']; ?>" onclick="return confirm('Activate this product?')">
                                                                <i class="fas fa-check-circle me-2"></i>Activate
                                                            </a></li>
                                                        <?php endif; ?>
                                                        
                                                        <?php if($product['featured']): ?>
                                                            <li><a class="dropdown-item" href="?action=unfeature&id=<?php echo $product['id']; ?>" onclick="return confirm('Unmark as featured?')">
                                                                <i class="fas fa-star me-2"></i>Unmark Featured
                                                            </a></li>
                                                        <?php else: ?>
                                                            <li><a class="dropdown-item" href="?action=feature&id=<?php echo $product['id']; ?>" onclick="return confirm('Mark as featured?')">
                                                                <i class="far fa-star me-2"></i>Mark Featured
                                                            </a></li>
                                                        <?php endif; ?>
                                                        
                                                        <li><hr class="dropdown-divider"></li>
                                                        <li><a class="dropdown-item text-danger" 
                                                               href="?action=delete&id=<?php echo $product['id']; ?>" 
                                                               onclick="return confirm('Are you sure you want to delete this product?')">
                                                            <i class="fas fa-trash me-2"></i>Delete
                                                        </a></li>
                                                    </ul>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                    <?php endwhile; ?>
                                <?php else: ?>
                                    <tr>
                                        <td colspan="7" class="text-center py-5">
                                            <i class="fas fa-box fa-3x mb-3" style="color: #ddd;"></i>
                                            <h4>No products found</h4>
                                            <p class="text-muted">Try adjusting your search or filter criteria</p>
                                            <a href="add-product.php" class="btn btn-orange">
                                                <i class="fas fa-plus me-2"></i>Add Your First Product
                                            </a>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </form>

        <!-- Pagination -->
        <?php if($total_pages > 1): ?>
        <nav aria-label="Page navigation" class="mt-4">
            <ul class="pagination justify-content-center">
                <li class="page-item <?php echo $page == 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo $page - 1; ?><?php echo isset($_GET['search']) ? '&search=' . urlencode($search) : ''; ?><?php echo $category ? '&category=' . $category : ''; ?><?php echo $status ? '&status=' . $status : ''; ?>">
                        <i class="fas fa-chevron-left"></i>
                    </a>
                </li>
                
                <?php for($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?><?php echo isset($_GET['search']) ? '&search=' . urlencode($search) : ''; ?><?php echo $category ? '&category=' . $category : ''; ?><?php echo $status ? '&status=' . $status : ''; ?>">
                            <?php echo $i; ?>
                        </a>
                    </li>
                <?php endfor; ?>
                
                <li class="page-item <?php echo $page == $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?page=<?php echo $page + 1; ?><?php echo isset($_GET['search']) ? '&search=' . urlencode($search) : ''; ?><?php echo $category ? '&category=' . $category : ''; ?><?php echo $status ? '&status=' . $status : ''; ?>">
                        <i class="fas fa-chevron-right"></i>
                    </a>
                </li>
            </ul>
        </nav>
        <?php endif; ?>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Select/Deselect all checkboxes
        function toggleSelectAll(source) {
            const checkboxes = document.querySelectorAll('.product-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = source.checked;
            });
        }
        
        function selectAll() {
            const checkboxes = document.querySelectorAll('.product-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = true;
            });
            document.getElementById('selectAll').checked = true;
        }
        
        function deselectAll() {
            const checkboxes = document.querySelectorAll('.product-checkbox');
            checkboxes.forEach(checkbox => {
                checkbox.checked = false;
            });
            document.getElementById('selectAll').checked = false;
        }
        
        // Update select all checkbox when individual checkboxes change
        document.querySelectorAll('.product-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', function() {
                const allChecked = Array.from(document.querySelectorAll('.product-checkbox')).every(cb => cb.checked);
                document.getElementById('selectAll').checked = allChecked;
            });
        });
        
        // Bulk action confirmation
        function confirmBulkAction() {
            const action = document.querySelector('select[name="bulk_action"]').value;
            const checked = document.querySelectorAll('.product-checkbox:checked').length;
            
            if (!action) {
                alert('Please select a bulk action');
                return false;
            }
            
            if (checked === 0) {
                alert('Please select at least one product');
                return false;
            }
            
            if (action === 'delete') {
                return confirm(`Are you sure you want to delete ${checked} product(s)? This action cannot be undone.`);
            }
            
            return true;
        }
    </script>
</body>
</html>