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

$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if (!$id) { header('Location: ' . SITE_URL . '/admin/products.php'); exit; }

$db = getDB();
$product = getProductById($id);
if (!$product) { header('Location: ' . SITE_URL . '/admin/products.php'); exit; }

$adminPageTitle = 'Edit: ' . $product['name'];
$errors  = [];
$success = '';

// Handle delete single image
if (isset($_GET['delete_image'])) {
    $imgId = (int)$_GET['delete_image'];
    $imgRow = $db->prepare("SELECT * FROM product_images WHERE id = ? AND product_id = ?");
    $imgRow->execute([$imgId, $id]);
    $imgRow = $imgRow->fetch();
    if ($imgRow) {
        @unlink(UPLOAD_DIR . $imgRow['image_path']);
        $db->prepare("DELETE FROM product_images WHERE id = ?")->execute([$imgId]);
        $_SESSION['flash'] = 'Image deleted.';
    }
    header('Location: ' . SITE_URL . '/admin/product_edit.php?id=' . $id);
    exit;
}

// Handle form submission
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');

    if (!$name) $errors[] = 'Product name is required.';
    if (!is_numeric($price) || $price < 0) $errors[] = 'Valid price is required.';

    // Count existing images
    $existingCount = (int)$db->prepare("SELECT COUNT(*) FROM product_images WHERE product_id = ?")->execute([$id]) ? 
                     $db->query("SELECT COUNT(*) FROM product_images WHERE product_id = $id")->fetchColumn() : 0;

    $uploadedFiles = [];
    if (!empty($_FILES['images']['name'][0])) {
        $allowedTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
        foreach ($_FILES['images']['tmp_name'] as $i => $tmp) {
            if (!$tmp || $_FILES['images']['error'][$i] !== UPLOAD_ERR_OK) continue;
            if ($existingCount + count($uploadedFiles) >= MAX_PRODUCT_IMAGES) {
                $errors[] = 'Image limit (' . MAX_PRODUCT_IMAGES . ') reached. Delete some existing images first.';
                break;
            }
            $mime = mime_content_type($tmp);
            if (!in_array($mime, $allowedTypes)) { $errors[] = 'Invalid image type.'; continue; }
            if ($_FILES['images']['size'][$i] > 5 * 1024 * 1024) { $errors[] = 'Image too large (max 5MB).'; continue; }
            $ext = strtolower(pathinfo($_FILES['images']['name'][$i], PATHINFO_EXTENSION));
            $filename = uniqid('prod_', true) . '.' . $ext;
            $uploadedFiles[] = ['tmp' => $tmp, 'filename' => $filename];
        }
    }

    if (empty($errors)) {
        $db->beginTransaction();
        try {
            $db->prepare("UPDATE products SET name=?, price=?, description=?, color=?, selling_status=? WHERE id=?")
               ->execute([$name, $price, $description, $color, $status, $id]);

            // Get current max sort order
            $maxOrder = (int)$db->query("SELECT MAX(sort_order) FROM product_images WHERE product_id = $id")->fetchColumn();
            $imgStmt = $db->prepare("INSERT INTO product_images (product_id, image_path, sort_order) VALUES (?, ?, ?)");
            foreach ($uploadedFiles as $idx => $file) {
                move_uploaded_file($file['tmp'], UPLOAD_DIR . $file['filename']);
                $imgStmt->execute([$id, $file['filename'], $maxOrder + $idx + 1]);
            }
            $db->commit();

            // Reload product data
            $product = getProductById($id);
            $success = 'Product updated successfully!';
        } catch (\Exception $e) {
            $db->rollBack();
            $errors[] = 'Error: ' . $e->getMessage();
        }
    }
}

$existingImages = getProductImages($id);
$canAddMore = count($existingImages) < MAX_PRODUCT_IMAGES;

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

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

<?php if ($success): ?>
<div class="alert alert-success alert-dismissible fade show mb-4">
    <i class="fas fa-check-circle me-2"></i><?= sanitize($success) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<?php if (!empty($_SESSION['flash'])): ?>
<div class="alert alert-info alert-dismissible fade show mb-4">
    <i class="fas fa-info-circle me-2"></i><?= sanitize($_SESSION['flash']) ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php unset($_SESSION['flash']); endif; ?>

<?php if ($errors): ?>
<div class="alert alert-danger mb-4">
    <ul class="mb-0"><?php foreach ($errors as $e): ?><li><?= sanitize($e) ?></li><?php endforeach; ?></ul>
</div>
<?php endif; ?>

<form method="POST" enctype="multipart/form-data">
    <!-- Product Info -->
    <div class="table-card mb-4">
        <div class="card-header">
            <i class="fas fa-tag me-2 text-primary"></i>Product Information
            <a href="<?= SITE_URL ?>/product.php?id=<?= $id ?>" target="_blank" class="btn btn-sm btn-outline-info float-end">
                <i class="fas fa-external-link-alt me-1"></i>View Live
            </a>
        </div>
        <div class="p-4">
            <div class="row g-3">
                <div class="col-md-8">
                    <label class="form-label fw-semibold">Product Name *</label>
                    <input type="text" name="name" class="form-control" value="<?= sanitize($product['name']) ?>" required>
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-semibold">Price (₹) *</label>
                    <div class="input-group">
                        <span class="input-group-text">₹</span>
                        <input type="number" name="price" class="form-control" step="0.01" min="0" value="<?= sanitize($product['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" value="<?= sanitize($product['color'] ?? '') ?>" placeholder="e.g. Midnight Black">
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-semibold">Selling Status *</label>
                    <select name="selling_status" class="form-select">
                        <option value="available" <?= $product['selling_status'] === 'available' ? 'selected' : '' ?>>✅ Available</option>
                        <option value="out_of_stock" <?= $product['selling_status'] === 'out_of_stock' ? 'selected' : '' ?>>❌ Out of Stock</option>
                        <option value="coming_soon" <?= $product['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"><?= sanitize($product['description'] ?? '') ?></textarea>
                </div>
            </div>
        </div>
    </div>

    <!-- Existing Images -->
    <div class="table-card mb-4">
        <div class="card-header">
            <i class="fas fa-images me-2 text-primary"></i>
            Current Images
            <span class="badge bg-<?= count($existingImages) >= MAX_PRODUCT_IMAGES ? 'danger' : 'secondary' ?> ms-2">
                <?= count($existingImages) ?>/<?= MAX_PRODUCT_IMAGES ?>
            </span>
        </div>
        <div class="p-4">
            <?php if (empty($existingImages)): ?>
                <p class="text-muted text-center py-3">No images uploaded yet.</p>
            <?php else: ?>
            <div class="row g-3">
                <?php foreach ($existingImages as $idx => $img): ?>
                <div class="col-4 col-md-3 col-xl-2" id="imgCard<?= $img['id'] ?>">
                    <div class="position-relative border rounded-3 overflow-hidden bg-light" style="height:120px;">
                        <img src="<?= UPLOAD_URL . sanitize($img['image_path']) ?>"
                             class="w-100 h-100"
                             style="object-fit:contain;padding:6px;"
                             alt="Image <?= $idx+1 ?>">
                        <div class="position-absolute top-0 start-0 bg-dark bg-opacity-50 text-white px-2 py-1 rounded-br" style="font-size:11px;">
                            #<?= $idx+1 ?>
                        </div>
                        <a href="?id=<?= $id ?>&delete_image=<?= $img['id'] ?>"
                           class="position-absolute top-0 end-0 m-1 btn btn-danger btn-sm"
                           style="width:26px;height:26px;padding:0;font-size:12px;display:flex;align-items:center;justify-content:center;"
                           onclick="return confirm('Delete this image?')">
                            <i class="fas fa-times"></i>
                        </a>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
            <?php endif; ?>

            <!-- Add More Images -->
            <?php if ($canAddMore): ?>
            <div class="mt-4">
                <label class="form-label fw-semibold">Add More Images (<?= MAX_PRODUCT_IMAGES - count($existingImages) ?> slot(s) left)</label>
                <input type="file" name="images[]" class="form-control" multiple accept="image/*"
                       onchange="validateNewImages(this, <?= MAX_PRODUCT_IMAGES - count($existingImages) ?>)">
                <small class="text-muted">JPG, PNG, WEBP, GIF — Max 5MB each</small>
            </div>
            <?php else: ?>
            <div class="alert alert-warning mt-4 mb-0">
                <i class="fas fa-exclamation-triangle me-2"></i>
                Maximum <?= MAX_PRODUCT_IMAGES ?> images reached. Delete some images above to add new ones.
            </div>
            <?php endif; ?>
        </div>
    </div>

    <!-- Buttons -->
    <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>Update Product
        </button>
        <a href="<?= SITE_URL ?>/admin/products.php" class="btn btn-outline-secondary btn-lg px-4">Back to Products</a>
    </div>
</form>
</div>
</div>

<?php
$maxSlots = MAX_PRODUCT_IMAGES - count($existingImages);
$extraJS = <<<JS
<script>
function validateNewImages(input, maxSlots) {
    if (input.files.length > maxSlots) {
        alert('You can only add ' + maxSlots + ' more image(s). You selected ' + input.files.length + '.');
        input.value = '';
    }
}
</script>
JS;
include __DIR__ . '/partials/admin_footer.php';
?>
