<?php
/**
 * Admin Products Management
 * Lists all products, handles secure deletion, and provides links to add/edit.
 */

// Include core files
require_once '../includes/config.php';
require_once '../includes/db.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
require_once '../includes/admin-auth.php';
require_once '../includes/csrf.php';

// -----------------------------------------------------------------------------
// 1. STRICT ACCESS CONTROL
// -----------------------------------------------------------------------------
require_admin($pdo);

// -----------------------------------------------------------------------------
// 2. HANDLE PRODUCT DELETION (POST)
// -----------------------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete') {
    enforce_csrf();
    
    $product_id = isset($_POST['product_id']) ? (int)$_POST['product_id'] : 0;

    if ($product_id > 0) {
        try {
            // Fetch product details to identify files for physical deletion
            $stmt_fetch = $pdo->prepare("SELECT main_image, file_path FROM products WHERE id = :id LIMIT 1");
            $stmt_fetch->bindParam(':id', $product_id, PDO::PARAM_INT);
            $stmt_fetch->execute();
            $product_to_delete = $stmt_fetch->fetch();

            if ($product_to_delete) {
                // Fetch screenshots to delete
                $stmt_ss = $pdo->prepare("SELECT image_path FROM product_screenshots WHERE product_id = :id");
                $stmt_ss->bindParam(':id', $product_id, PDO::PARAM_INT);
                $stmt_ss->execute();
                $screenshots = $stmt_ss->fetchAll();

                // 1. Delete physical files securely using defined paths
                $main_image_path = PRODUCT_IMAGES_PATH . DS . $product_to_delete['main_image'];
                $zip_file_path = PRODUCT_FILES_PATH . DS . $product_to_delete['file_path'];
                
                if (file_exists($main_image_path) && is_file($main_image_path)) {
                    unlink($main_image_path);
                }
                if (file_exists($zip_file_path) && is_file($zip_file_path)) {
                    unlink($zip_file_path);
                }

                foreach ($screenshots as $ss) {
                    $ss_path = PRODUCT_SCREENSHOTS_PATH . DS . $ss['image_path'];
                    if (file_exists($ss_path) && is_file($ss_path)) {
                        unlink($ss_path);
                    }
                }

                // 2. Delete from database (Foreign keys handle cascading deletes for orders and screenshots)
                $stmt_delete = $pdo->prepare("DELETE FROM products WHERE id = :id");
                $stmt_delete->bindParam(':id', $product_id, PDO::PARAM_INT);
                $stmt_delete->execute();

                set_flash_message('success', 'Product and all associated files deleted successfully.');
            } else {
                set_flash_message('error', 'Product not found.');
            }
        } catch (PDOException $e) {
            error_log("Product Deletion Error: " . $e->getMessage());
            set_flash_message('error', 'A system error occurred while trying to delete the product.');
        }
    }
    
    redirect(SITE_URL . '/admin/products.php');
}

// -----------------------------------------------------------------------------
// 3. FETCH ALL PRODUCTS WITH STATS
// -----------------------------------------------------------------------------
try {
    // Subquery to count approved orders (sales) for each product
    $query = "
        SELECT 
            p.id, p.title, p.slug, p.price, p.status, p.created_at, p.main_image,
            (SELECT COUNT(*) FROM orders o WHERE o.product_id = p.id AND o.status = 'approved') AS total_sales
        FROM products p
        ORDER BY p.created_at DESC
    ";
    $stmt = $pdo->query($query);
    $products = $stmt->fetchAll();
} catch (PDOException $e) {
    error_log("Admin Products Fetch Error: " . $e->getMessage());
    $products = [];
}

// Set header variables
$page_title = "Manage Products";
require_once '../includes/header.php';
?>

<style>
    /* Admin Sub-Navigation (Reused from Dashboard) */
    .admin-nav {
        background: var(--bg-glass);
        border: 1px solid var(--border-color);
        border-radius: var(--radius-md);
        padding: 16px 24px;
        margin-bottom: 32px;
        display: flex;
        gap: 24px;
        flex-wrap: wrap;
        align-items: center;
    }
    .admin-nav-link {
        color: var(--text-secondary);
        font-weight: 600;
        font-size: 0.95rem;
        transition: color var(--transition-fast);
        display: flex;
        align-items: center;
        gap: 8px;
    }
    .admin-nav-link:hover, .admin-nav-link.active {
        color: var(--accent-orange);
    }
    .admin-nav-divider {
        width: 1px;
        height: 24px;
        background: var(--border-color);
    }

    /* Table Styles */
    .admin-panel-section {
        margin-bottom: 48px;
    }
    .section-heading {
        font-size: 1.5rem;
        margin-bottom: 24px;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    .table-container {
        width: 100%;
        overflow-x: auto;
    }
    .data-table {
        width: 100%;
        border-collapse: collapse;
        text-align: left;
    }
    .data-table th, .data-table td {
        padding: 16px;
        border-bottom: 1px solid var(--border-color);
        font-size: 0.95rem;
        vertical-align: middle;
    }
    .data-table th {
        color: var(--text-muted);
        font-weight: 600;
        text-transform: uppercase;
        font-size: 0.8rem;
        letter-spacing: 0.05em;
        background: rgba(0, 0, 0, 0.2);
    }
    .data-table tr:last-child td {
        border-bottom: none;
    }
    .data-table tbody tr:hover {
        background: rgba(255, 255, 255, 0.02);
    }
    
    .product-thumbnail {
        width: 60px;
        height: 40px;
        object-fit: cover;
        border-radius: var(--radius-sm);
        border: 1px solid var(--border-color);
    }

    .status-badge {
        display: inline-block;
        padding: 4px 10px;
        border-radius: 20px;
        font-size: 0.75rem;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.05em;
    }
    .status-active { background: rgba(16, 185, 129, 0.1); color: #10b981; border: 1px solid rgba(16, 185, 129, 0.3); }
    .status-hidden { background: rgba(239, 68, 68, 0.1); color: #ef4444; border: 1px solid rgba(239, 68, 68, 0.3); }

    .action-buttons {
        display: flex;
        gap: 8px;
    }
    .btn-sm {
        padding: 6px 12px;
        font-size: 0.8rem;
    }
</style>

<div class="container">
    
    <div style="margin-bottom: 24px;">
        <h1 style="font-size: 2rem;">Product Management</h1>
        <p class="text-secondary">Manage your digital catalog, add new assets, and track sales.</p>
    </div>

    <nav class="admin-nav">
        <a href="<?php echo SITE_URL; ?>/admin/dashboard.php" class="admin-nav-link">
            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="9"></rect><rect x="14" y="3" width="7" height="5"></rect><rect x="14" y="12" width="7" height="9"></rect><rect x="3" y="16" width="7" height="5"></rect></svg>
            Dashboard
        </a>
        <a href="<?php echo SITE_URL; ?>/admin/products.php" class="admin-nav-link active">
            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path></svg>
            Products
        </a>
        <a href="<?php echo SITE_URL; ?>/admin/orders.php" class="admin-nav-link">
            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="9" cy="21" r="1"></circle><circle cx="20" cy="21" r="1"></circle><path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"></path></svg>
            Orders
        </a>
        <a href="<?php echo SITE_URL; ?>/admin/users.php" class="admin-nav-link">
            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"></path><circle cx="9" cy="7" r="4"></circle><path d="M23 21v-2a4 4 0 0 0-3-3.87"></path><path d="M16 3.13a4 4 0 0 1 0 7.75"></path></svg>
            Users
        </a>
        <a href="<?php echo SITE_URL; ?>/admin/settings.php" class="admin-nav-link">
            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>
            Settings
        </a>
    </nav>

    <div class="admin-panel-section glass-card">
        <div class="section-heading">
            <h2 style="font-size: 1.25rem;">All Products</h2>
            <a href="<?php echo SITE_URL; ?>/admin/add-product.php" class="btn btn-glow">
                <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="margin-right: 6px;"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>
                Add New Product
            </a>
        </div>
        
        <?php if (!empty($products)): ?>
            <div class="table-container">
                <table class="data-table">
                    <thead>
                        <tr>
                            <th>Image</th>
                            <th>Title & Slug</th>
                            <th>Price</th>
                            <th>Sales</th>
                            <th>Status</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($products as $product): ?>
                            <tr>
                                <td>
                                    <img src="<?php echo SITE_URL . '/storage/product_images/' . htmlspecialchars($product['main_image']); ?>" alt="Thumbnail" class="product-thumbnail" onerror="this.src='<?php echo SITE_URL; ?>/assets/images/placeholder.jpg';">
                                </td>
                                <td>
                                    <div style="font-weight: 600; color: var(--text-primary);"><?php echo htmlspecialchars($product['title']); ?></div>
                                    <div style="font-size: 0.8rem; color: var(--text-muted); font-family: monospace;">/<?php echo htmlspecialchars($product['slug']); ?></div>
                                </td>
                                <td style="font-weight: 500;"><?php echo format_price($product['price']); ?></td>
                                <td><?php echo number_format($product['total_sales']); ?></td>
                                <td>
                                    <?php if ($product['status'] === 'active'): ?>
                                        <span class="status-badge status-active">Active</span>
                                    <?php else: ?>
                                        <span class="status-badge status-hidden">Hidden</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <div class="action-buttons">
                                        <a href="<?php echo SITE_URL; ?>/admin/edit-product.php?id=<?php echo $product['id']; ?>" class="btn btn-outline btn-sm">Edit</a>
                                        
                                        <form action="<?php echo SITE_URL; ?>/admin/products.php" method="POST" style="display:inline;">
                                            <?php echo csrf_field(); ?>
                                            <input type="hidden" name="action" value="delete">
                                            <input type="hidden" name="product_id" value="<?php echo $product['id']; ?>">
                                            <button type="submit" class="btn btn-outline btn-sm" style="color: var(--danger); border-color: var(--danger);" data-confirm="Are you absolutely sure you want to delete this product? This action cannot be undone and will remove physical files.">Delete</button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php else: ?>
            <div style="text-align: center; padding: 60px 0;">
                <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--text-muted)" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" style="margin-bottom: 16px;"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"></path></svg>
                <p class="text-secondary" style="font-size: 1.1rem; margin-bottom: 16px;">Your product catalog is currently empty.</p>
                <a href="<?php echo SITE_URL; ?>/admin/add-product.php" class="btn btn-glow">Add Your First Product</a>
            </div>
        <?php endif; ?>
    </div>

</div>

<?php require_once '../includes/footer.php'; ?>