<?php
session_start();
// Recalculate roles directly from database to avoid stale session values
require_once __DIR__ . '/db_config.php';

$userId = $_SESSION['user_id'] ?? null;
if (!$userId) {
    header('Location: admin_login.php');
    exit;
}

// default roles
$isAdmin = false;
$isSubadmin = false;
$isEditor = false;

if ($conn) {
    // check admins table if it exists
    try {
        $t = $conn->query("SHOW TABLES LIKE 'admins'");
        if ($t && $t->num_rows > 0) {
            $q = $conn->query("SELECT id FROM admins WHERE user_id = " . intval($userId) . " LIMIT 1");
            if ($q && $q->num_rows > 0) {
                $isAdmin = true;
            }
        }
    } catch (Throwable $e) {
        // ignore; treat as not admin
    }
    // check subadmins table
    try {
        $q2 = $conn->query("SELECT id FROM subadmins WHERE user_id = " . intval($userId) . " LIMIT 1");
        if ($q2 && $q2->num_rows > 0) {
            $isSubadmin = true;
        }
    } catch (Throwable $e) {
        // ignore
    }
    // check editors table
    try {
        $q3 = $conn->query("SELECT id FROM editors WHERE user_id = " . intval($userId) . " LIMIT 1");
        if ($q3 && $q3->num_rows > 0) {
            $isEditor = true;
        }
    } catch (Throwable $e) {
        // ignore
    }
}

// enforce access: admins, subadmins or editors with manage_products permission
if (!$isAdmin) {
    if (!$isSubadmin) {
        $editor_permissions = $_SESSION['editor_permissions'] ?? [];
        if (!isset($editor_permissions['manage_products']) || $editor_permissions['manage_products'] !== 'editor') {
            header('Location: index.php');
            exit;
        }
    }
}

// update session with accurate role flags (clear stale values)

define('SESSION_ROLE_RESET', true); // marker for debugging
$_SESSION['is_admin'] = $isAdmin;
$_SESSION['is_subadmin'] = $isSubadmin;
$_SESSION['is_editor'] = $isEditor;

// Load DatabaseHelper and ImageHandler
require_once __DIR__ . '/helpers/database_helper.php';
require_once __DIR__ . '/config/image_config.php';

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

// Load categories for dropdown
$categories = DatabaseHelper::loadJson('categories.json', []);

// Also collect categories from existing products
$productCats = [];
foreach ($products as $p) {
    if (!empty($p['cat']) && !in_array($p['cat'], $productCats)) {
        $productCats[] = $p['cat'];
    }
}

// Merge categories: if a category from products isn't in the main list, add it
$categoryNames = array_column($categories, 'name');
foreach ($productCats as $pcat) {
    if (!in_array($pcat, $categoryNames)) {
        $categories[] = ['id' => null, 'name' => $pcat, 'parent_id' => null];
    }
}

$error = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $price = (float)($_POST['price'] ?? 0);
    $cat = trim($_POST['cat'] ?? '');
    $desc = trim($_POST['desc'] ?? '');
    $tags = trim($_POST['tags'] ?? '');
    $brand = trim($_POST['brand'] ?? '');
    $rating = isset($_POST['rating']) ? (float)$_POST['rating'] : null;
    $salePrice = isset($_POST['sale_price']) && $_POST['sale_price'] !== '' ? (float)$_POST['sale_price'] : null;
    $onSale = isset($_POST['on_sale']) ? true : false;
    $featured = isset($_POST['featured']) ? true : false;
    
    // Handle multiple sizes
    $sizes = [];
    if (!empty($_POST['sizes']) && is_array($_POST['sizes'])) {
        $sizes = array_map('trim', $_POST['sizes']);
    }
    
    $image = '';
    $gallery = [];
    $colors = [];
    $video = '';
    
    // Handle main image with ImageHandler
    if (!empty($_FILES['image']['tmp_name']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
        $result = uploadProductImage($_FILES['image'], $title);
        if ($result['success']) {
            $image = $result['filename'];
        }
    }
    // Handle gallery images - fix for multiple files
    if (isset($_FILES['gallery'])) {
        $galleryCount = count($_FILES['gallery']['tmp_name']);
        for ($i = 0; $i < $galleryCount; $i++) {
            if (!empty($_FILES['gallery']['tmp_name'][$i]) && $_FILES['gallery']['error'][$i] === UPLOAD_ERR_OK) {
                $origName = $_FILES['gallery']['name'][$i];
                $dest = __DIR__ . '/pics_ecom/' . basename($origName);
                if (move_uploaded_file($_FILES['gallery']['tmp_name'][$i], $dest)) {
                    $gallery[] = 'pics_ecom/' . basename($origName);
                }
            }
        }
    }
    // Handle product video upload
    if (!empty($_FILES['video']['tmp_name']) && $_FILES['video']['error'] === UPLOAD_ERR_OK) {
        $videoName = basename($_FILES['video']['name']);
        $videoExt = strtolower(pathinfo($videoName, PATHINFO_EXTENSION));
        $allowedVideoExts = ['mp4', 'webm', 'mov', 'avi', 'mkv'];
        
        if (in_array($videoExt, $allowedVideoExts)) {
            $videoFileName = 'video_' . time() . '_' . rand(1000, 9999) . '.' . $videoExt;
            $videoDest = __DIR__ . '/pics_ecom/' . $videoFileName;
            if (move_uploaded_file($_FILES['video']['tmp_name'], $videoDest)) {
                $video = 'pics_ecom/' . $videoFileName;
            }
        }
    }
    // swatches
    $s=[];

    if(isset($_POST['swatches'])){
        $s=$_POST['swatches'];
    } if(!empty($s)){
        $swatches=array();
        foreach($s as $swatch){
            $swatches[]=trim($swatch);
        }
    }

    // Handle color images with color codes
    if (isset($_FILES['color_images'])) {
        $colorCount = count($_FILES['color_images']['tmp_name']);
        $colorNames = $_POST['color_names'] ?? [];
        $colorCodes = $_POST['color_codes'] ?? [];
        
        for ($i = 0; $i < $colorCount; $i++) {
            $colorName = trim($colorNames[$i] ?? '');
            $colorCode = trim($colorCodes[$i] ?? '#cccccc');
            
            if (!empty($colorName)) {
                $colorData = [
                    'name' => $colorName,
                    'code' => $colorCode
                ];
                
                // Only add image if one was uploaded
                if (!empty($_FILES['color_images']['tmp_name'][$i]) && $_FILES['color_images']['error'][$i] === UPLOAD_ERR_OK) {
                    $origName = $_FILES['color_images']['name'][$i];
                    $dest = __DIR__ . '/pics_ecom/' . basename($origName);
                    if (move_uploaded_file($_FILES['color_images']['tmp_name'][$i], $dest)) {
                        $colorData['image'] = 'pics_ecom/' . basename($origName);
                    }
                }
                
                $colors[] = $colorData;
            }
        }
    }
    if ($title && $price) {
        $id = 1;
        $srNo = 1;
        foreach ($products as $p) {
            if ($p['id'] >= $id) $id = $p['id'] + 1;
            if (!empty($p['sr_no']) && $p['sr_no'] >= $srNo) $srNo = $p['sr_no'] + 1;
        }
        $newProduct = [
            'id' => $id, 
            'sr_no' => $srNo,
            'title' => $title, 
            'price' => $price, 
            'cat' => $cat, 
            'desc' => $desc, 
            'tags' => $tags,
            'image' => $image,
            'gallery' => $gallery
        ];
        
        // Add video if provided
        if (!empty($video)) {
            $newProduct['video'] = $video;
        }
        
        // Add brand if provided
        if (!empty($brand)) {
            $newProduct['brand'] = $brand;
        }
        
        // Add rating if provided
        if ($rating !== null && $rating > 0) {
            $newProduct['rating'] = $rating;
        }
        
        // Add sale price if provided
        if ($salePrice !== null && $salePrice > 0) {
            $newProduct['sale_price'] = $salePrice;
            $newProduct['on_sale'] = true;
        } elseif ($onSale) {
            $newProduct['on_sale'] = true;
        }
        
        // Add featured flag if checked
        if ($featured) {
            $newProduct['featured'] = true;
        }
        
        // Add sizes if any were selected
        if (!empty($sizes)) {
            $newProduct['sizes'] = $sizes;
        }
        // Add colors if any were uploaded
        if (!empty($colors)) {
            $newProduct['colors'] = $colors;
        }
        $products[] = $newProduct;
        
        // Save using DatabaseHelper with proper error handling
        if (DatabaseHelper::saveJson('products.json', $products)) {
            $_SESSION['success'] = 'Product added successfully!';
            header('Location: admin_products.php');
            exit;
        } else {
            $error = 'Failed to save product. Please check file permissions and try again.';
        }
    } else {
        $error = 'Title and price are required.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>Add Product - Admin</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
<?php // no sidebar or dashboard button for any role ?>
<?php // Admin pages don't include the main site header ?>
<main style="padding: 24px;">
    <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:16px;">
        <h1 style="margin:0;">Add Product</h1>
        <a href="admin_products.php" class="btn" style="background:#F07E2D; color:#fff; text-decoration:none; padding:8px 12px; border-radius:6px;">← Back to Products</a>
    </div>
    <?php if ($error): ?>
    <p class="muted"><?php echo htmlspecialchars($error); ?></p>
    <?php endif; ?>
    <form method="post" enctype="multipart/form-data" style="display:flex;flex-direction:column;gap:8px;max-width:600px;background:#fff;padding:16px;border-radius:8px;">
        <input type="text" name="title" placeholder="Title" required>
        <input type="number" name="price" step="0.01" placeholder="Price" required>
        <label style="font-weight:600;">Category:</label>
        <select name="cat" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px;">
            <option value="">-- Select Category --</option>
            <?php 
            // Group categories by parent
            foreach ($categories as $cat):
                if (empty($cat['parent_id'])): // Top-level categories
            ?>
                <option value="<?php echo htmlspecialchars($cat['name']); ?>"><?php echo htmlspecialchars($cat['name']); ?></option>
                <?php 
                    // Show subcategories under parent
                    foreach ($categories as $subcat):
                        if ($subcat['parent_id'] === $cat['id']):
                ?>
                    <option value="<?php echo htmlspecialchars($subcat['name']); ?>" style="padding-left:20px;">→ <?php echo htmlspecialchars($subcat['name']); ?></option>
                <?php 
                        endif;
                    endforeach;
                endif;
            endforeach; 
            ?>
        </select>
        <label style="font-weight:600; margin-top:8px;">Available Sizes (optional - select multiple):</label>
        <div style="background:#f9f9f9; padding:12px; border-radius:6px; display:grid; grid-template-columns:repeat(auto-fill, minmax(120px, 1fr)); gap:10px;">
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="XS"> XS (Extra Small)</label>
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="S"> S (Small)</label>
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="M"> M (Medium)</label>
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="L"> L (Large)</label>
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="XL"> XL (Extra Large)</label>
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="XXL"> XXL (2X Large)</label>
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="XS-S"> XS-S</label>
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="S-M"> S-M</label>
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="M-L"> M-L</label>
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="L-XL"> L-XL</label>
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="XL-XXL"> XL-XXL</label>
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="One Size"> One Size Fits All</label>
            <label style="font-weight:normal; display:flex; align-items:center; gap:8px;"><input type="checkbox" name="sizes[]" value="Free Size"> Free Size</label>
        </div>
        <textarea name="desc" placeholder="Description" style="resize:vertical; min-height:80px;"></textarea>
        <input type="text" name="tags" placeholder="Tags (e.g., dress, summer, casual, cotton) - separated by comma" style="padding:8px;">
        
        <label style="font-weight:600; margin-top:8px;">Brand:</label>
        <?php
        $brandsFile = __DIR__ . '/data/brands.json';
        $brandsList = [];
        if (file_exists($brandsFile)) {
            $brandsData = json_decode(file_get_contents($brandsFile), true);
            if (is_array($brandsData)) {
                $brandsList = $brandsData;
            }
        }
        ?>
        <input type="text" name="brand" list="brands-list" placeholder="Enter brand name (optional)" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px;">
        <datalist id="brands-list">
            <?php foreach ($brandsList as $brand): ?>
                <option value="<?php echo htmlspecialchars($brand['name']); ?>">
            <?php endforeach; ?>
        </datalist>
        
        <label style="font-weight:600; margin-top:8px;">Rating (0-5):</label>
        <input type="number" name="rating" step="0.1" min="0" max="5" placeholder="e.g., 4.5" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px;">
        
        <label style="font-weight:600; margin-top:8px;">Sale Price (Optional - leave empty if not on sale):</label>
        <input type="number" name="sale_price" step="0.01" min="0" placeholder="e.g., 29.99" style="padding:8px; border:1px solid #e6e6e6; border-radius:6px;">
        <label style="font-weight:600; display:flex; align-items:center; gap:8px; margin-top:4px;">
            <input type="checkbox" name="on_sale"> Mark as On Sale
        </label>
        
        <label style="font-weight:600; display:flex; align-items:center; gap:8px; margin-top:8px;">
            <input type="checkbox" name="featured"> Mark as Featured Product
        </label>
        <label style="font-weight:600; margin-top:4px;">Main Product Image (optional): <input type="file" name="image" accept="image/*"></label>
        <label style="font-weight:600;">Gallery Images (optional - select multiple files): <input type="file" name="gallery[]" accept="image/*" multiple></label>
        <p style="font-size:12px; color:#666; margin:-6px 0 8px 0;">Hold Ctrl/Cmd and click to select multiple images. Customers will see the main image in shop view and can switch between gallery images when viewing the product.</p>
        
        <label style="font-weight:600; margin-top:8px; color:#F07E2D;">Product Video (optional - MP4, WebM, MOV, AVI, MKV): <input type="file" name="video" accept="video/*"></label>
        <p style="font-size:12px; color:#666; margin:-6px 0 8px 0;">Upload a short video for your product. Video will auto-play when customers hover over it on the shop page. Video can also be selected as the main image or gallery image in the product detail page.</p>
        
        <hr style="margin:12px 0; border:none; border-top:1px solid #eee;">
        <label style="font-weight:600; color:#F07E2D;">Color Swatches (Optional)</label>
        <p style="font-size:12px; color:#666; margin-top:-4px; margin-bottom:8px;">Upload different images for each color. Customers will see circular color swatches on the product page and the main image will change when they click a color swatch.</p>
        
        <!-- Color Swatches Preview -->
        <div id="colorSwatchesPreview" style="background:#f9f9f9; padding:12px; border-radius:6px; margin-bottom:12px; display:none;">
          <strong style="font-size:12px; display:block; margin-bottom:8px;">Color Swatch Preview:</strong>
          <div id="previewContainer" style="display:flex; gap:8px; flex-wrap:wrap;"></div>
        </div>
        
        <!-- Color Variants Input Container -->
        <div id="colorVariantsContainer" style="background:#f9f9f9; padding:12px; border-radius:6px; max-height:400px; overflow-y:auto;">
            <div class="color-variant" style="display:flex; gap:8px; align-items:flex-end; margin-bottom:8px; padding:8px; background:#fff; border-radius:4px;">
                <div style="flex:1;">
                    <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Color Name</label>
                    <input type="text" name="color_names[]" placeholder="e.g., Red, Blue, Black" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
                </div>
                <div style="flex:1;">
                    <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Color (Hex Code)</label>
                    <input type="color" name="color_codes[]" value="#FF0000" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px; height:38px;" onchange="updateSwatchPreview()">
                </div>
                <div style="flex:1;">
                    <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Product Image</label>
                    <input type="file" name="color_images[]" accept="image/*" style="width:100%; padding:4px; border:1px solid #ddd; border-radius:4px;" onchange="updateSwatchPreview()">
                </div>
                <button type="button" onclick="removeColorVariant(this)" class="btn" style="background:#dc3545; padding:6px 12px; font-size:12px; align-self:center;">Remove</button>
            </div>
        </div>  
        <button type="button" onclick="addColorVariant()" class="btn" style="background:#28a745; margin-top:8px; width:fit-content;">+ Add Another Color</button>
        <button class="btn" type="submit" style="margin-top:12px;">Save Product</button>
    </form>
</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');
}

function addColorVariant() {
    const container = document.getElementById('colorVariantsContainer');
    const newVariant = document.createElement('div');
    newVariant.className = 'color-variant';
    newVariant.style.cssText = 'display:flex; gap:8px; align-items:flex-end; margin-bottom:8px; padding:8px; background:#fff; border-radius:4px;';
    newVariant.innerHTML = `
        <div style="flex:1;">
            <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Color Name</label>
            <input type="text" name="color_names[]" placeholder="e.g., Red, Blue, Black" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px;">
        </div>
        <div style="flex:1;">
            <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Color (Hex Code)</label>
            <input type="color" name="color_codes[]" value="#FF0000" style="width:100%; padding:8px; border:1px solid #ddd; border-radius:4px; height:38px;" onchange="updateSwatchPreview()">
        </div>
        <div style="flex:1;">
            <label style="font-size:12px; color:#666; display:block; margin-bottom:4px;">Product Image</label>
            <input type="file" name="color_images[]" accept="image/*" style="width:100%; padding:4px; border:1px solid #ddd; border-radius:4px;" onchange="updateSwatchPreview()">
        </div>
        <button type="button" onclick="removeColorVariant(this)" class="btn" style="background:#dc3545; padding:6px 12px; font-size:12px; align-self:center;">Remove</button>
    `;
    container.appendChild(newVariant);
}

function removeColorVariant(btn) {
    btn.parentElement.remove();
    updateSwatchPreview();   
}

function updateSwatchPreview() {
    const colorNames = document.querySelectorAll('input[name="color_names[]"]');
    const colorCodes = document.querySelectorAll('input[name="color_codes[]"]');
    const previewContainer = document.getElementById('previewContainer');
    const previewSection = document.getElementById('colorSwatchesPreview');
    
    previewContainer.innerHTML = '';
    let hasSwatches = false;
    
    colorNames.forEach((nameInput, index) => {
        const name = nameInput.value.trim();
        const colorCode = colorCodes[index] ? colorCodes[index].value : '#ccc';
        
        if (name && colorCode) {
            hasSwatches = true;
            const swatch = document.createElement('div');
            swatch.style.cssText = `
                width: 50px;
                height: 50px;
                border-radius: 50%;
                background-color: ${colorCode};
                border: 3px solid #ddd;
                cursor: pointer;
                transition: all 0.3s ease;
                position: relative;
                display: flex;
                align-items: flex-end;
                justify-content: center;
                box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            `;
            swatch.title = name;
            
            const label = document.createElement('span');
            label.textContent = name;
            label.style.cssText = `
                position: absolute;
                bottom: -25px;
                font-size: 11px;
                font-weight: 600;
                color: #333;
                white-space: nowrap;
            `;
            swatch.appendChild(label);
            
            previewContainer.appendChild(swatch);
        }
    });
    
    previewSection.style.display = hasSwatches ? 'block' : 'none';
}

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');
    }
    updateSwatchPreview();
});
</script>
</body>
</html>
