<?php
session_start();
require_once __DIR__ . '/../includes/config.php';
requireAdminLogin();

$adminPageTitle = 'Add New Product';
$errors = [];
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name        = trim($_POST['name'] ?? '');
    $price       = trim($_POST['price'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $color       = trim($_POST['color'] ?? '');
    $status      = trim($_POST['selling_status'] ?? 'available');

    // Validate
    if (!$name)  $errors[] = 'Product name is required.';
    if (!is_numeric($price) || $price < 0) $errors[] = 'Valid price is required.';
    if (!in_array($status, ['available', 'out_of_stock', 'coming_soon'])) $errors[] = 'Invalid status.';

    // Validate images
    $uploadedFiles = [];
    if (!empty($_FILES['images']['name'][0])) {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
        $totalImages  = count(array_filter($_FILES['images']['name']));
        if ($totalImages > MAX_PRODUCT_IMAGES) {
            $errors[] = 'Maximum ' . MAX_PRODUCT_IMAGES . ' images allowed.';
        } else {
            foreach ($_FILES['images']['tmp_name'] as $i => $tmp) {
                if (!$tmp || $_FILES['images']['error'][$i] !== UPLOAD_ERR_OK) continue;
                $mime = mime_content_type($tmp);
                if (!in_array($mime, $allowedTypes)) {
                    $errors[] = 'File "' . htmlspecialchars($_FILES['images']['name'][$i]) . '" is not a valid image.';
                    continue;
                }
                if ($_FILES['images']['size'][$i] > 5 * 1024 * 1024) {
                    $errors[] = 'File "' . htmlspecialchars($_FILES['images']['name'][$i]) . '" exceeds 5MB limit.';
                    continue;
                }
                $ext = strtolower(pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION));
                $filename = uniqid('prod_', true) . '.' . $ext;
                $uploadedFiles[] = ['tmp' => $tmp, 'filename' => $filename];
            }
        }
    }

    if (empty($errors)) {
        $db = getDB();
        $db->beginTransaction();
        try {
            // Insert product
            $stmt = $db->prepare("INSERT INTO products (name, price, description, color, selling_status) VALUES (?, ?, ?, ?, ?)");
            $stmt->execute([$name, $price, $description, $color, $status]);
            $productId = (int)$db->lastInsertId();

            // Move images and insert records
            $imgStmt = $db->prepare("INSERT INTO product_images (product_id, image_path, sort_order) VALUES (?, ?, ?)");
            foreach ($uploadedFiles as $idx => $file) {
                $dest = UPLOAD_DIR . $file['filename'];
                if (!move_uploaded_file($file['tmp'], $dest)) {
                    throw new \RuntimeException('Failed to save image: ' . $file['filename']);
                }
                $imgStmt->execute([$productId, $file['filename'], $idx]);
            }

            $db->commit();
            $_SESSION['flash'] = 'Product "' . $name . '" added successfully!';
            header('Location: ' . SITE_URL . '/admin/products.php');
            exit;
        } catch (\Exception $e) {
            $db->rollBack();
            $errors[] = 'Database error: ' . $e->getMessage();
        }
    }
}

include __DIR__ . '/partials/admin_header.php';
?>

<div class="row justify-content-center">
<div class="col-xl-9 col-lg-11">

<?php if ($errors): ?>
<div class="alert alert-danger mb-4">
    <strong><i class="fas fa-exclamation-triangle me-2"></i>Please fix the following:</strong>
    <ul class="mb-0 mt-2">
        <?php foreach ($errors as $e): ?><li><?= sanitize($e) ?></li><?php endforeach; ?>
    </ul>
</div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data">
    <!-- Product Info Card -->
    <div class="table-card mb-4">
        <div class="card-header"><i class="fas fa-tag me-2 text-primary"></i>Product Information</div>
        <div class="p-4">
            <div class="row g-3">
                <div class="col-md-8">
                    <label class="form-label fw-semibold">Product Name <span class="text-danger">*</span></label>
                    <input type="text" name="name" class="form-control" placeholder="e.g. Samsung 4K Smart TV 55&quot;" value="<?= sanitize($_POST['name'] ?? '') ?>" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-semibold">Price (₹) <span class="text-danger">*</span></label>
                    <div class="input-group">
                        <span class="input-group-text">₹</span>
                        <input type="number" name="price" class="form-control" placeholder="0.00" step="0.01" min="0" value="<?= sanitize($_POST['price'] ?? '') ?>" required>
                    </div>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-semibold">Color</label>
                    <input type="text" name="color" class="form-control" placeholder="e.g. Midnight Black, Silver" value="<?= sanitize($_POST['color'] ?? '') ?>">
                    <small class="text-muted">Used for color swatch on product page</small>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-semibold">Selling Status <span class="text-danger">*</span></label>
                    <select name="selling_status" class="form-select">
                        <option value="available" <?= (($_POST['selling_status'] ?? '') === 'available') ? 'selected' : '' ?>>✅ Available</option>
                        <option value="out_of_stock" <?= (($_POST['selling_status'] ?? '') === 'out_of_stock') ? 'selected' : '' ?>>❌ Out of Stock</option>
                        <option value="coming_soon" <?= (($_POST['selling_status'] ?? '') === 'coming_soon') ? 'selected' : '' ?>>🕐 Coming Soon</option>
                    </select>
                </div>
                <div class="col-12">
                    <label class="form-label fw-semibold">Description</label>
                    <textarea name="description" class="form-control" rows="5" placeholder="Detailed product description..."><?= sanitize($_POST['description'] ?? '') ?></textarea>
                </div>
            </div>
        </div>
    </div>

    <!-- Image Upload Card -->
    <div class="table-card mb-4">
        <div class="card-header">
            <i class="fas fa-images me-2 text-primary"></i>Product Images
            <span class="badge bg-secondary ms-2">Up to <?= MAX_PRODUCT_IMAGES ?> photos</span>
        </div>
        <div class="p-4">
            <div class="border-2 border-dashed rounded-3 p-4 text-center bg-light" id="dropZone">
                <i class="fas fa-cloud-upload-alt fa-3x text-muted mb-3"></i>
                <h6 class="mb-1">Drag & drop images here, or click to select</h6>
                <p class="text-muted small mb-3">JPG, PNG, WEBP, GIF — Max 5MB each — Up to <?= MAX_PRODUCT_IMAGES ?> images</p>
                <input type="file" name="images[]" id="imageInput" multiple accept="image/*" class="d-none" onchange="previewImages(this)">
                <button type="button" class="btn btn-outline-primary" onclick="document.getElementById('imageInput').click()">
                    <i class="fas fa-folder-open me-2"></i>Choose Images
                </button>
            </div>

            <!-- Preview Grid -->
            <div id="imagePreview" class="row g-3 mt-3"></div>
            <div id="imageCount" class="text-muted small mt-2"></div>
        </div>
    </div>

    <!-- Submit -->
    <div class="d-flex gap-3">
        <button type="submit" class="btn btn-success btn-lg px-5">
            <i class="fas fa-save me-2"></i>Save Product
        </button>
        <a href="<?= SITE_URL ?>/admin/products.php" class="btn btn-outline-secondary btn-lg px-4">Cancel</a>
    </div>
</form>
</div>
</div>

<style>
.border-dashed { border-style: dashed !important; }
#dropZone { cursor: pointer; transition: background .2s; }
#dropZone:hover { background: #e8f0fe !important; }
.preview-thumb { position: relative; }
.preview-thumb img { width: 100%; height: 130px; object-fit: cover; border-radius: 8px; }
.preview-thumb .remove-btn { position: absolute; top: 5px; right: 5px; background: rgba(220,53,69,.85); color: white; border: none; border-radius: 50%; width: 26px; height: 26px; font-size: 12px; cursor: pointer; display: flex; align-items: center; justify-content: center; }
</style>

<?php
$extraJS = <<<JS
<script>
const MAX_IMAGES = <?= MAX_PRODUCT_IMAGES ?>;
let selectedFiles = [];

function previewImages(input) {
    const files = Array.from(input.files);
    if (selectedFiles.length + files.length > MAX_IMAGES) {
        alert('Maximum ' + MAX_IMAGES + ' images allowed. You already have ' + selectedFiles.length + '.');
        input.value = '';
        return;
    }
    files.forEach(f => { if (f.type.startsWith('image/')) selectedFiles.push(f); });
    renderPreviews();
    syncFileInput();
}

function renderPreviews() {
    const grid = document.getElementById('imagePreview');
    const count = document.getElementById('imageCount');
    grid.innerHTML = '';
    selectedFiles.forEach((f, i) => {
        const col = document.createElement('div');
        col.className = 'col-4 col-md-3 preview-thumb';
        const url = URL.createObjectURL(f);
        col.innerHTML = \`<img src="\${url}" alt=""><button type="button" class="remove-btn" onclick="removeImage(\${i})"><i class="fas fa-times"></i></button>\`;
        grid.appendChild(col);
    });
    count.textContent = selectedFiles.length + '/' + MAX_IMAGES + ' image(s) selected';
}

function removeImage(idx) {
    selectedFiles.splice(idx, 1);
    renderPreviews();
    syncFileInput();
}

function syncFileInput() {
    const dt = new DataTransfer();
    selectedFiles.forEach(f => dt.items.add(f));
    document.getElementById('imageInput').files = dt.files;
}

// Drag & drop
const zone = document.getElementById('dropZone');
zone.addEventListener('dragover', e => { e.preventDefault(); zone.style.background = '#e8f0fe'; });
zone.addEventListener('dragleave', () => { zone.style.background = ''; });
zone.addEventListener('drop', e => {
    e.preventDefault();
    zone.style.background = '';
    const input = document.getElementById('imageInput');
    const dt = e.dataTransfer;
    const newFiles = Array.from(dt.files).filter(f => f.type.startsWith('image/'));
    if (selectedFiles.length + newFiles.length > MAX_IMAGES) {
        alert('Maximum ' + MAX_IMAGES + ' images allowed.');
        return;
    }
    newFiles.forEach(f => selectedFiles.push(f));
    renderPreviews();
    syncFileInput();
});
</script>
JS;
include __DIR__ . '/partials/admin_footer.php';
?>
