<?php
/**
 * Manage Products (100% Mobile Responsive List View - Premium Light Green UI)
 */
require_once 'header.php';

$success = '';
$error = '';

// ==========================================
// ১. প্রোডাক্ট ডিলিট করার লজিক
// ==========================================
if (isset($_GET['delete'])) {
    $del_id = (int)$_GET['delete'];
    
    // ডাটাবেস থেকে ফাইলের নামগুলো তুলে আনা
    $stmt = $pdo->prepare("SELECT main_image, download_file FROM products WHERE id = ?");
    $stmt->execute([$del_id]);
    $prod = $stmt->fetch();
    
    if ($prod) {
        // ফোল্ডার থেকে ছবি ও জিপ ফাইল রিমুভ করা
        if (!empty($prod['main_image']) && file_exists('../uploads/products/images/' . $prod['main_image'])) {
            unlink('../uploads/products/images/' . $prod['main_image']);
        }
        if (!empty($prod['download_file']) && file_exists('../uploads/products/files/' . $prod['download_file'])) {
            unlink('../uploads/products/files/' . $prod['download_file']);
        }
        
        // ডিলিট স্ক্রিনশট
        $stmt_sc = $pdo->prepare("SELECT image FROM product_screenshots WHERE product_id = ?");
        $stmt_sc->execute([$del_id]);
        $screenshots = $stmt_sc->fetchAll();
        foreach($screenshots as $sc) {
            if(file_exists('../uploads/products/screenshots/' . $sc['image'])) {
                @unlink('../uploads/products/screenshots/' . $sc['image']);
            }
        }
        
        // ডাটাবেস থেকে ডিলিট করা
        $pdo->prepare("DELETE FROM products WHERE id = ?")->execute([$del_id]);
        $success = "Product and files have been successfully deleted!";
    }
}

// ==========================================
// ২. সব প্রোডাক্ট লিস্ট ফেচ করা
// ==========================================
$query = "
    SELECT p.*, c.name as cat_name 
    FROM products p 
    LEFT JOIN categories c ON p.category_id = c.id 
    ORDER BY p.id DESC
";
$products = $pdo->query($query)->fetchAll();

$currency = defined('CURRENCY_SYMBOL') ? CURRENCY_SYMBOL : 'BDT ';
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/toastify-js/src/toastify.min.css">
<style>
    :root {
        --primary: #84cc16; /* Light Green */
        --primary-hover: #65a30d;
        --bg-light: #f8fafc;
        --card-bg: #ffffff;
        --border: #e2e8f0;
        --text-main: #1e293b;
        --text-muted: #64748b;
    }

    body { background: var(--bg-light); color: var(--text-main); font-family: 'Inter', sans-serif; margin: 0; }
    
    .settings-container { max-width: 1200px; margin: 0 auto; padding: 20px; }

    /* ================= Header ================= */
    .page-header { 
        display: flex; justify-content: space-between; align-items: center; margin-bottom: 25px; flex-wrap: wrap; gap: 15px;
    }
    .page-title { font-size: 1.5rem; font-weight: 800; color: var(--text-main); margin: 0; }
    
    .btn-primary { 
        background: var(--primary); color: #fff; padding: 10px 20px; border-radius: 8px; font-size: 0.9rem; font-weight: 700; text-decoration: none; display: inline-flex; align-items: center; gap: 8px; transition: 0.3s; box-shadow: none; border: none;
    }
    .btn-primary:hover { background: var(--primary-hover); transform: translateY(-1px); }

    /* ================= Responsive Table Design ================= */
    .table-card { 
        background: var(--card-bg); border: 1px solid var(--border); border-radius: 12px; padding: 20px; box-shadow: none; margin-bottom: 30px;
    }
    
    /* Table Wrapper for Horizontal Scroll on Mobile */
    .table-responsive { 
        width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; 
    }
    .data-table { width: 100%; border-collapse: collapse; text-align: left; min-width: 800px; }
    .data-table th { padding: 15px 12px; font-size: 0.8rem; color: var(--text-muted); font-weight: 700; border-bottom: 1px solid var(--border); text-transform: uppercase; white-space: nowrap; background: #fafafa;}
    .data-table td { padding: 15px 12px; border-bottom: 1px solid var(--border); font-size: 0.9rem; color: var(--text-main); font-weight: 500; vertical-align: middle; }
    .data-table tr:last-child td { border-bottom: none; }
    .data-table tr:hover { background: #fdfdfd; }
    
    .prod-img { width: 50px; height: 50px; border-radius: 8px; object-fit: cover; border: 1px solid var(--border); padding: 2px; background: #fff; display: block;}

    /* ================= Badges & Buttons ================= */
    .status-badge { padding: 4px 10px; border-radius: 20px; font-size: 0.7rem; font-weight: 800; text-transform: uppercase; display: inline-block; white-space: nowrap;}
    .status-active { background: #ecfdf5; color: #10b981; border: 1px solid #a7f3d0; }
    .status-inactive { background: #f1f5f9; color: #64748b; border: 1px solid #cbd5e1; }
    
    .action-btn { font-size: 0.8rem; font-weight: 700; text-decoration: none; padding: 8px 14px; border-radius: 6px; transition: 0.2s; display: inline-flex; align-items: center; gap: 5px; white-space: nowrap; box-shadow: 0 1px 2px rgba(0,0,0,0.05);}
    .btn-edit { color: #ffffff; background: #3b82f6; border: 1px solid transparent; }
    .btn-edit:hover { background: #2563eb; transform: translateY(-1px); }
    .btn-delete { color: #ffffff; background: #ef4444; margin-left: 5px; border: 1px solid transparent; }
    .btn-delete:hover { background: #dc2626; transform: translateY(-1px); }

    .file-badge { font-size: 0.7rem; background: #f4fce3; color: var(--primary-hover); padding: 4px 8px; border-radius: 4px; display: inline-block; font-weight: 700; white-space: nowrap; border: 1px solid #d9f99d;}

    /* Toast */
    .toast-success { background: #10b981 !important; color: #fff !important; font-weight: 600; border-radius: 6px !important; box-shadow: none !important; border: 1px solid #059669 !important; padding: 10px 20px !important; }
    .toast-error { background: #ef4444 !important; color: #fff !important; font-weight: 600; border-radius: 6px !important; box-shadow: none !important; border: 1px solid #b91c1c !important; padding: 10px 20px !important; }

    /* ================= Mobile Adjustments ================= */
    @media (max-width: 768px) {
        .settings-container { padding: 15px 10px; }
        .page-header { flex-direction: column; align-items: flex-start; gap: 15px; }
        .table-card { padding: 15px 10px; }
        .data-table th, .data-table td { padding: 12px 10px; }
    }
</style>

<div class="settings-container">
    <div class="page-header">
        <h1 class="page-title">Digital Products</h1>
        <a href="add-product.php" class="btn-primary">
            <svg width="18" height="18" fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4"/></svg>
            New Product
        </a>
    </div>

    <div class="table-card">
        <div class="table-responsive">
            <table class="data-table">
                <thead>
                    <tr>
                        <th style="width: 60px;">Image</th>
                        <th>Title & Category</th>
                        <th>Price</th>
                        <th>Source File</th>
                        <th>Status</th>
                        <th style="text-align: right;">Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach($products as $prod): ?>
                    <tr>
                        <td>
                            <img src="../uploads/products/images/<?php echo htmlspecialchars($prod['main_image']); ?>" alt="Img" class="prod-img" onerror="this.src='https://via.placeholder.com/50';">
                        </td>
                        
                        <td>
                            <div style="color: var(--text-main); font-weight: 700; margin-bottom: 4px; white-space: normal; min-width: 180px; line-height: 1.3;">
                                <?php echo htmlspecialchars($prod['title']); ?>
                            </div>
                            <div style="font-size: 0.8rem; color: var(--text-muted); font-weight: 600;">
                                Cat: <?php echo htmlspecialchars($prod['cat_name'] ?? 'Uncategorized'); ?>
                            </div>
                        </td>
                        
                        <td>
                            <div style="font-weight: 800; color: var(--text-main);"><?php echo $currency . number_format($prod['price'], 2); ?></div>
                            <?php if($prod['old_price'] > 0): ?>
                                <div style="font-size: 0.75rem; color: var(--text-muted); text-decoration: line-through; font-weight: 600;">
                                    <?php echo $currency . number_format($prod['old_price'], 2); ?>
                                </div>
                            <?php endif; ?>
                        </td>
                        
                        <td>
                            <?php if(!empty($prod['download_file'])): ?>
                                <span class="file-badge">ZIP Attached</span>
                            <?php else: ?>
                                <span class="file-badge" style="background: #fef2f2; color: #ef4444; border-color: #fecaca;">Missing File</span>
                            <?php endif; ?>
                        </td>

                        <td>
                            <?php if($prod['status'] == 'active'): ?>
                                <span class="status-badge status-active">Active</span>
                            <?php else: ?>
                                <span class="status-badge status-inactive">Hidden</span>
                            <?php endif; ?>
                        </td>
                        
                        <td style="text-align: right; white-space: nowrap;">
                            <a href="edit-product.php?id=<?php echo $prod['id']; ?>" class="action-btn btn-edit">
                                <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"/></svg>
                                Edit
                            </a>
                            <a href="?delete=<?php echo $prod['id']; ?>" class="action-btn btn-delete" onclick="return confirm('Are you sure you want to delete this product and its files? This action cannot be undone!');">
                                <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                Delete
                            </a>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    
                    <?php if(empty($products)): ?>
                        <tr>
                            <td colspan="6" style="text-align: center; padding: 40px; color: var(--text-muted); font-weight: 500;">
                                No digital products found. Click "New Product" to add your first item.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/toastify-js"></script>
<script>
    <?php if($success): ?>
    Toastify({
        text: "<?php echo addslashes($success); ?>",
        duration: 3000,
        gravity: "top", 
        position: "center",
        className: "toast-success",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>

    <?php if($error): ?>
    Toastify({
        text: "<?php echo addslashes($error); ?>",
        duration: 4000,
        gravity: "top", 
        position: "center",
        className: "toast-error",
        stopOnFocus: true
    }).showToast();
    <?php endif; ?>
</script>

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