<?php
// admin/products.php
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';

if (!isAdmin()) {
    header('Location: login.php');
    exit;
}

// Check for session messages
$success_msg = $_SESSION['success_msg'] ?? '';
$error_msg = $_SESSION['error_msg'] ?? '';
unset($_SESSION['success_msg']);
unset($_SESSION['error_msg']);

// Get all products
$stmt = $pdo->query("SELECT p.*, c.name as category_name 
                     FROM products p 
                     LEFT JOIN categories c ON p.category_id = c.id 
                     ORDER BY p.created_at DESC");
$products = $stmt->fetchAll();

include 'header.php';
?>

<div class="admin-card">
    <div class="d-flex justify-content-between align-items-center">
        <h5 class="card-title">Products (<?php echo count($products); ?>)</h5>
        <a href="add-product.php" class="btn btn-primary">
            <i class="fa-solid fa-plus"></i> Add Product
        </a>
    </div>
    
    <!-- Alert Container -->
    <div id="alertContainer"></div>
    
    <?php if ($success_msg): ?>
    <div class="alert alert-success alert-dismissible fade show mt-3" role="alert" id="successAlert">
        <i class="fa-solid fa-check-circle me-2"></i> <?php echo htmlspecialchars($success_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>
    
    <?php if ($error_msg): ?>
    <div class="alert alert-danger alert-dismissible fade show mt-3" role="alert" id="errorAlert">
        <i class="fa-solid fa-exclamation-circle me-2"></i> <?php echo htmlspecialchars($error_msg); ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php endif; ?>
    
    <div class="table-responsive mt-3">
        <table class="table table-hover">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Image</th>
                    <th>Name</th>
                    <th>Category</th>
                    <th>Price</th>
                    <th>Sale Price</th>
                    <th>Stock</th>
                    <th>Status</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody id="productsTableBody">
                <?php if (empty($products)): ?>
                <tr id="noDataRow"><td colspan="9" class="text-center">No products found</td></tr>
                <?php else: ?>
                <?php foreach ($products as $product): ?>
                <tr id="productRow_<?php echo $product['id']; ?>">
                    <td><?php echo $product['id']; ?></td>
                    <td>
                        <?php if ($product['image']): ?>
                        <img src="../assets/images/products/<?php echo $product['image']; ?>" 
                             alt="<?php echo $product['name']; ?>" 
                             style="width:50px; height:50px; object-fit:cover; border-radius:8px;">
                        <?php else: ?>
                        <span class="text-muted">No image</span>
                        <?php endif; ?>
                    </td>
                    <td><strong><?php echo substr($product['name'], 0, 30) . (strlen($product['name']) > 30 ? '...' : ''); ?></strong></td>
                    <td><?php echo $product['category_name'] ?? 'N/A'; ?></td>
                    <td><?php echo number_format($product['price']); ?> TK</td>
                    <td><?php echo $product['sale_price'] ? number_format($product['sale_price']) . ' TK' : '-'; ?></td>
                    <td><?php echo $product['stock']; ?></td>
                    <td>
                        <span class="badge bg-<?php echo $product['status'] ? 'success' : 'danger'; ?>">
                            <?php echo $product['status'] ? 'Active' : 'Inactive'; ?>
                        </span>
                    </td>
                    <td>
                        <a href="edit-product.php?id=<?php echo $product['id']; ?>" class="btn btn-sm btn-warning">
                            <i class="fa-solid fa-edit"></i>
                        </a>
                        <button onclick="deleteProduct(<?php echo $product['id']; ?>, '<?php echo addslashes($product['name']); ?>')" class="btn btn-sm btn-danger">
                            <i class="fa-solid fa-trash"></i>
                        </button>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Delete Product</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <p>Are you sure you want to delete this product?</p>
                <p class="text-danger"><strong>Warning:</strong> This action cannot be undone.</p>
                <p><strong>Product:</strong> <span id="deleteProductName"></span></p>
                <input type="hidden" id="delete_product_id">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-danger" id="confirmDeleteBtn">Delete Permanently</button>
            </div>
        </div>
    </div>
</div>

<script>
function deleteProduct(id, name) {
    document.getElementById('delete_product_id').value = id;
    document.getElementById('deleteProductName').textContent = name;
    var modal = new bootstrap.Modal(document.getElementById('deleteModal'));
    modal.show();
}

// Handle delete confirmation with AJAX
document.getElementById('confirmDeleteBtn').addEventListener('click', function() {
    var id = document.getElementById('delete_product_id').value;
    var btn = this;
    var originalText = btn.innerHTML;
    
    // Disable button and show loading
    btn.disabled = true;
    btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Deleting...';
    
    // Create form data
    var formData = new FormData();
    formData.append('id', id);
    
    // Send AJAX request
    fetch('delete-product-ajax.php', {
        method: 'POST',
        body: formData
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok: ' + response.status);
        }
        return response.json();
    })
    .then(data => {
        // Close modal
        var modal = bootstrap.Modal.getInstance(document.getElementById('deleteModal'));
        modal.hide();
        
        if (data.success) {
            // Remove the row from table
            var row = document.getElementById('productRow_' + id);
            if (row) {
                row.style.transition = 'all 0.5s ease';
                row.style.opacity = '0';
                setTimeout(function() {
                    row.remove();
                    // Check if no rows left
                    var tbody = document.getElementById('productsTableBody');
                    if (tbody.children.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="9" class="text-center">No products found</td></tr>';
                    }
                }, 500);
            }
            
            // Show success message
            showAlert('success', data.name ? 'Product "' + data.name + '" deleted successfully!' : 'Product deleted successfully!');
        } else {
            showAlert('danger', data.message || 'Failed to delete product');
        }
        
        // Reset button
        btn.disabled = false;
        btn.innerHTML = originalText;
    })
    .catch(error => {
        console.error('Error:', error);
        showAlert('danger', 'Something went wrong. Please try again.');
        
        // Reset button
        btn.disabled = false;
        btn.innerHTML = originalText;
    });
});

// Function to show alert
function showAlert(type, message) {
    var alertContainer = document.getElementById('alertContainer');
    var alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';
    
    var alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show mt-3" role="alert">
            <i class="fa-solid ${icon} me-2"></i> ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
        </div>
    `;
    
    alertContainer.innerHTML = alertHtml;
    
    // Auto dismiss after 5 seconds
    setTimeout(function() {
        var alert = alertContainer.querySelector('.alert');
        if (alert) {
            alert.style.transition = 'opacity 0.5s ease';
            alert.style.opacity = '0';
            setTimeout(function() {
                alert.remove();
            }, 500);
        }
    }, 5000);
}

// Auto hide session alerts after 5 seconds
document.addEventListener('DOMContentLoaded', function() {
    var alerts = document.querySelectorAll('.alert');
    alerts.forEach(function(alert) {
        setTimeout(function() {
            if (alert) {
                alert.style.transition = 'opacity 0.5s ease';
                alert.style.opacity = '0';
                setTimeout(function() {
                    alert.remove();
                }, 500);
            }
        }, 5000);
    });
});
</script>

<?php include 'footer.php'; ?>