<?php
session_start();
if (empty($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    header('Location: admin_login.php');
    exit;
}

require_once __DIR__ . '/helpers/database_helper.php';

$products = DatabaseHelper::loadJson('products.json', []);
$categories = DatabaseHelper::loadJson('categories.json', []);

// Create category map for quick lookup
$categoryMap = [];
foreach ($categories as $cat) {
    $categoryMap[$cat['id']] = $cat['name'];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    if ($action === 'delete') {
        $id = (int)($_POST['id'] ?? 0);
        $products = array_values(array_filter($products, function($p) use ($id){ return $p['id'] !== $id; }));
        if (DatabaseHelper::saveJson('products.json', $products)) {
            $_SESSION['success'] = 'Product deleted successfully!';
        } else {
            $_SESSION['error'] = 'Failed to delete product';
        }
        header('Location: admin_products.php');
        exit;
    }
    
    if ($action === 'toggle_featured') {
        $id = (int)($_POST['id'] ?? 0);
        $saved = false;
        foreach ($products as &$p) {
            if ($p['id'] === $id) {
                $p['featured'] = !($p['featured'] ?? false);
                $saved = DatabaseHelper::saveJson('products.json', $products);
                break;
            }
        }
        if ($saved) {
            $_SESSION['success'] = 'Product featured status updated!';
        } else {
            $_SESSION['error'] = 'Failed to update product';
        }
        header('Location: admin_products.php');
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Manage Products - Admin</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body class="admin-with-sidebar">
<?php include __DIR__ . '/admin_sidebar.php'; ?>
<?php // Admin pages don't include the main site header ?>
<main class="admin-main-content" style="padding: 24px;">
    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:16px;">
        <h1 style="margin:0;">Products</h1>
        <a href="admin_dashboard.php" class="btn" style="background:#F07E2D; color:#fff; text-decoration:none; padding:8px 12px; border-radius:6px;">← Back to Dashboard</a>
    </div>
    <?php if (!empty($_SESSION['success'])): ?>
    <div style="background:#d4edda; color:#155724; padding:12px; border-radius:6px; margin-bottom:16px; border:1px solid #c3e6cb;">
        <?php echo htmlspecialchars($_SESSION['success']); ?>
        <?php unset($_SESSION['success']); ?>
    </div>
    <?php endif; ?>
    
    <?php 
    // Check if migration is needed
    $migrationFlagFile = __DIR__ . '/data/.sr_no_migration_done';
    $needsMigration = false;
    if (!file_exists($migrationFlagFile) && !empty($products)) {
        // Check if any product is missing sr_no
        foreach ($products as $p) {
            if (empty($p['sr_no'])) {
                $needsMigration = true;
                break;
            }
        }
    }
    ?>
    
    <?php if ($needsMigration): ?>
    <div style="background:#fff3cd; color:#856404; padding:16px; border-radius:6px; margin-bottom:16px; border:1px solid #ffeeba; display:flex; justify-content:space-between; align-items:center;">
        <div>
            <strong>⚠ SR NO Migration Required</strong>
            <p style="margin:8px 0 0 0; font-size:13px;">Your existing products need unique serial numbers for QR code generation. This is a one-time migration.</p>
        </div>
        <a href="migrate_add_sr_no.php" class="btn" style="background:#ffc107; color:#000; text-decoration:none; padding:8px 16px; border-radius:6px; font-weight:bold; white-space:nowrap; margin-left:16px;">Run Migration</a>
    </div>
    <?php endif; ?>
    
    <p><a href="admin_add_product.php" class="btn">Add Product</a></p>
    <table style="width:100%;border-collapse:collapse;">
        <thead>
            <tr>
                <th style="text-align:left;padding:8px">Title</th>
                <th style="padding:8px">Price</th>
                <th style="padding:8px">Category</th>
                <th style="padding:8px">Featured</th>
                <th style="padding:8px">Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($products as $p): ?>
            <tr>
                <td style="padding:8px"><?php echo htmlspecialchars($p['title'] ?? $p['name'] ?? 'Untitled'); ?></td>
                <td style="padding:8px">$<?php echo isset($p['price']) ? number_format($p['price'], 2) : '0.00'; ?></td>
                <td style="padding:8px"><?php 
                    // Get category name from category_id or cat field
                    $catName = '';
                    if (!empty($p['category_id']) && isset($categoryMap[$p['category_id']])) {
                        $catName = $categoryMap[$p['category_id']];
                    } elseif (!empty($p['cat'])) {
                        $catName = $p['cat'];
                    }
                    echo htmlspecialchars($catName);
                ?></td>
                <td style="padding:8px; text-align:center;">
                    <form method="post" action="admin_products.php" style="display:inline;">
                        <input type="hidden" name="action" value="toggle_featured">
                        <input type="hidden" name="id" value="<?php echo $p['id']; ?>">
                        <button type="submit" style="background:none; border:none; cursor:pointer; font-size:18px; padding:0;" title="Toggle Featured">
                            <?php echo (!empty($p['featured']) ? '⭐' : '☆'); ?>
                        </button>
                    </form>
                </td>
                <td style="padding:8px;">
                    <a href="admin_edit_product.php?id=<?php echo $p['id']; ?>" class="btn">Edit</a>
                    <form method="post" action="admin_products.php" style="display:inline; margin-left:8px;" onsubmit="return confirm('Delete this product?');">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="id" value="<?php echo $p['id']; ?>">
                        <button class="btn" type="submit" style="background:#999;">Delete</button>
                    </form>
                </td>
            </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</main>
<?php include __DIR__ . '/footer.php'; ?>
<script>
function toggleAdminSidebar() {
    const sidebar = document.getElementById('adminSidebarContainer');
    const mainContent = document.querySelector('.admin-main-content');
    sidebar.classList.toggle('collapsed');
    mainContent.classList.toggle('with-collapsed-sidebar');
    localStorage.setItem('adminSidebarCollapsed', sidebar.classList.contains('collapsed') ? '1' : '0');
}
document.addEventListener('DOMContentLoaded', function() {
    const isCollapsed = localStorage.getItem('adminSidebarCollapsed') === '1';
    if (isCollapsed) {
        document.getElementById('adminSidebarContainer').classList.add('collapsed');
        document.querySelector('.admin-main-content').classList.add('with-collapsed-sidebar');
    }
});
</script>
</body>
</html>
