<?php
// ------------------------------------------------------------
// 1. Load DB + helpers BEFORE any HTML output
// ------------------------------------------------------------
require_once '../config/database.php';
require_once '../includes/functions.php';
require_once '../includes/auth.php';
requireLogin();

// Media base URL
define('MEDIA_BASE_URL', 'https://admin.vocabpanda.com/admin_panel/assets/uploads/');

// ------------------------------------------------------------
// 2. Fetch the product (or redirect if invalid)
// ------------------------------------------------------------
$id = $_GET['id'] ?? null;
if (!$id) {
    setFlash('danger', 'No product ID provided.');
    header('Location: products.php');
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM products WHERE id = :id");
$stmt->execute([':id' => $id]);
$product = $stmt->fetch();
if (!$product) {
    setFlash('danger', 'Product not found.');
    header('Location: products.php');
    exit;
}

// Fetch existing images
$imgStmt = $pdo->prepare("SELECT * FROM product_images WHERE product_id = :pid ORDER BY sort_order");
$imgStmt->execute([':pid' => $id]);
$existingImages = $imgStmt->fetchAll();

// Fetch dropdown data (categories & brands) – only needed for the form
$categories = $pdo->query("SELECT id, name FROM categories ORDER BY name")->fetchAll();
$brands     = $pdo->query("SELECT id, name FROM brands ORDER BY name")->fetchAll();

$errors = [];

// ------------------------------------------------------------
// 3. Handle POST – update & redirect on success
// ------------------------------------------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $product_code       = trim($_POST['product_code'] ?? '');
    $name               = trim($_POST['name'] ?? '');
    $category_id        = (int)($_POST['category_id'] ?? 0);
    $brand_id           = $_POST['brand_id'] !== '' ? (int)$_POST['brand_id'] : null;
    $buying_price       = (float)($_POST['buying_price'] ?? 0);
    $default_sell_price = (float)($_POST['default_sell_price'] ?? 0);
    $stock_qty          = (int)($_POST['stock_qty'] ?? 0);
    $is_in_stock        = $stock_qty > 0 ? 1 : (int)($_POST['is_in_stock'] ?? 1);
    $section_tag        = $_POST['section_tag'] ?? null;
    $description        = trim($_POST['description'] ?? '');
    $video_url          = trim($_POST['video_url'] ?? ''); // 🆕 video URL

    if ($product_code === '' || $name === '' || $category_id === 0) {
        $errors[] = 'Product code, name, and category are required.';
    }
    $slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $name)));

    // --- Thumbnail handling (full URL) ---
    $thumbnail = $product['thumbnail_url'];
    $thumbRaw  = null; // to clean up in case of error
    if (!empty($_FILES['thumbnail']['name'])) {
        $thumbRaw = uploadFile('thumbnail', ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], '../assets/uploads/');
        if ($thumbRaw === false) {
            $errors[] = 'Thumbnail upload failed.';
        } else {
            // Delete old thumbnail file (extract filename from full URL)
            if ($thumbnail) {
                $oldFile = basename(parse_url($thumbnail, PHP_URL_PATH));
                if ($oldFile) deleteFile('../assets/uploads/' . $oldFile);
            }
            // Store full URL
            $thumbnail = MEDIA_BASE_URL . $thumbRaw;
        }
    } elseif (isset($_POST['remove_thumbnail']) && $_POST['remove_thumbnail'] == 1) {
        if ($thumbnail) {
            $oldFile = basename(parse_url($thumbnail, PHP_URL_PATH));
            if ($oldFile) deleteFile('../assets/uploads/' . $oldFile);
        }
        $thumbnail = null;
    }

    // --- Remove selected additional images (full URL) ---
    if (isset($_POST['remove_images']) && is_array($_POST['remove_images'])) {
        foreach ($_POST['remove_images'] as $imgId) {
            $imgId = (int)$imgId;
            foreach ($existingImages as $img) {
                if ($img['id'] == $imgId) {
                    $oldFile = basename(parse_url($img['image_url'], PHP_URL_PATH));
                    if ($oldFile) deleteFile('../assets/uploads/' . $oldFile);
                    $pdo->prepare("DELETE FROM product_images WHERE id = :id")->execute([':id' => $imgId]);
                    break;
                }
            }
        }
    }

    // --- New additional images (store full URLs) ---
    $rawNewImages = uploadMultipleFiles('images', ['image/jpeg', 'image/png', 'image/gif', 'image/webp'], '../assets/uploads/');
    $newImageUrls = array_map(function($fn) {
        return MEDIA_BASE_URL . $fn;
    }, $rawNewImages);

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            // Update product (now includes video_url)
            $stmt = $pdo->prepare("UPDATE products SET
                category_id = :category_id,
                brand_id = :brand_id,
                product_code = :product_code,
                name = :name,
                slug = :slug,
                description = :description,
                buying_price = :buying_price,
                default_sell_price = :default_sell_price,
                stock_qty = :stock_qty,
                is_in_stock = :is_in_stock,
                thumbnail_url = :thumbnail_url,
                video_url = :video_url,
                section_tag = :section_tag
                WHERE id = :id
            ");
            $stmt->execute([
                ':category_id'        => $category_id,
                ':brand_id'           => $brand_id,
                ':product_code'       => $product_code,
                ':name'               => $name,
                ':slug'               => $slug,
                ':description'        => $description,
                ':buying_price'       => $buying_price,
                ':default_sell_price' => $default_sell_price,
                ':stock_qty'          => $stock_qty,
                ':is_in_stock'        => $is_in_stock,
                ':thumbnail_url'      => $thumbnail,
                ':video_url'          => $video_url ?: null, // 🆕
                ':section_tag'        => $section_tag,
                ':id'                 => $id,
            ]);

            // Insert new additional images
            if (!empty($newImageUrls)) {
                $maxSort = $pdo->prepare("SELECT COALESCE(MAX(sort_order), -1) FROM product_images WHERE product_id = :pid");
                $maxSort->execute([':pid' => $id]);
                $sort = $maxSort->fetchColumn() + 1;
                $imgInsert = $pdo->prepare("INSERT INTO product_images (product_id, image_url, sort_order) VALUES (:pid, :url, :sort)");
                foreach ($newImageUrls as $url) {
                    $imgInsert->execute([':pid' => $id, ':url' => $url, ':sort' => $sort++]);
                }
            }

            $pdo->commit();
            setFlash('success', 'Product updated successfully.');
            header('Location: products.php');
            exit;
        } catch (Exception $e) {
            $pdo->rollBack();
            $errors[] = 'Database error: ' . $e->getMessage();
            // Clean newly uploaded files on error
            if ($thumbRaw) deleteFile('../assets/uploads/' . $thumbRaw);
            foreach ($rawNewImages as $fn) deleteFile('../assets/uploads/' . $fn);
        }
    }
    // If errors, we'll continue to display the form below after including the header
}
?>

<?php
// ------------------------------------------------------------
// 4. Now include the full layout (header + sidebar) because we didn't redirect
// ------------------------------------------------------------
require_once '../includes/header.php';
?>

<h1 class="h2 mb-4">Edit Product #<?= $product['id'] ?></h1>

<?php if ($errors): ?>
<div class="alert alert-danger"><ul class="mb-0"><?php foreach ($errors as $e) echo '<li>'.htmlspecialchars($e).'</li>'; ?></ul></div>
<?php endif; ?>

<div class="card shadow-sm">
    <div class="card-body">
        <form method="POST" enctype="multipart/form-data">
            <div class="row">
                <!-- Basic Info -->
                <div class="col-md-6 mb-3">
                    <label class="form-label">Product Code *</label>
                    <input type="text" name="product_code" class="form-control" value="<?= htmlspecialchars($_POST['product_code'] ?? $product['product_code']) ?>" required>
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Product Name *</label>
                    <input type="text" name="name" class="form-control" value="<?= htmlspecialchars($_POST['name'] ?? $product['name']) ?>" required>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Category *</label>
                    <select name="category_id" class="form-select" required>
                        <option value="">Select</option>
                        <?php foreach ($categories as $cat): ?>
                            <option value="<?= $cat['id'] ?>" <?= ($_POST['category_id'] ?? $product['category_id']) == $cat['id'] ? 'selected' : '' ?>><?= htmlspecialchars($cat['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Brand</label>
                    <select name="brand_id" class="form-select">
                        <option value="">— None —</option>
                        <?php foreach ($brands as $b): ?>
                            <option value="<?= $b['id'] ?>" <?= ($_POST['brand_id'] ?? $product['brand_id']) == $b['id'] ? 'selected' : '' ?>><?= htmlspecialchars($b['name']) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-4 mb-3">
                    <label class="form-label">Section Tag</label>
                    <select name="section_tag" class="form-select">
                        <option value="">— None —</option>
                        <?php foreach (['featured','new','sale'] as $tag): ?>
                            <option value="<?= $tag ?>" <?= ($_POST['section_tag'] ?? $product['section_tag']) == $tag ? 'selected' : '' ?>><?= ucfirst($tag) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <!-- Pricing & Stock -->
                <div class="col-md-6 mb-3">
                    <label class="form-label">Buying Price</label>
                    <input type="number" step="0.01" name="buying_price" class="form-control" value="<?= htmlspecialchars($_POST['buying_price'] ?? $product['buying_price']) ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">Sell Price *</label>
                    <input type="number" step="0.01" name="default_sell_price" class="form-control" value="<?= htmlspecialchars($_POST['default_sell_price'] ?? $product['default_sell_price']) ?>" required>
                </div>

                <div class="col-md-6 mb-3">
                    <label class="form-label">Stock Qty</label>
                    <input type="number" name="stock_qty" class="form-control" value="<?= htmlspecialchars($_POST['stock_qty'] ?? $product['stock_qty']) ?>">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label">In Stock?</label>
                    <select name="is_in_stock" class="form-select">
                        <option value="1" <?= ($_POST['is_in_stock'] ?? $product['is_in_stock']) == 1 ? 'selected' : '' ?>>Yes</option>
                        <option value="0" <?= ($_POST['is_in_stock'] ?? $product['is_in_stock']) == 0 ? 'selected' : '' ?>>No</option>
                    </select>
                </div>

                <!-- Description -->
                <div class="col-12 mb-3">
                    <label class="form-label">Description</label>
                    <textarea name="description" class="form-control" rows="4"><?= htmlspecialchars($_POST['description'] ?? $product['description']) ?></textarea>
                </div>

                <!-- 🆕 Video URL -->
                <div class="col-12 mb-3">
                    <label class="form-label">Video URL <small class="text-muted">(YouTube / direct MP4)</small></label>
                    <input type="url" name="video_url" class="form-control" value="<?= htmlspecialchars($_POST['video_url'] ?? $product['video_url'] ?? '') ?>" placeholder="e.g. https://youtube.com/watch?v=...">
                </div>

                <!-- Thumbnail (full URL used directly) -->
                <div class="col-md-6 mb-3">
                    <label class="form-label">Thumbnail</label>
                    <?php if ($product['thumbnail_url']): ?>
                        <div class="mb-2">
                            <img src="<?= htmlspecialchars($product['thumbnail_url']) ?>" width="100" class="rounded">
                            <div class="form-check mt-1">
                                <input class="form-check-input" type="checkbox" name="remove_thumbnail" value="1" id="remove_thumbnail">
                                <label class="form-check-label" for="remove_thumbnail">Remove thumbnail</label>
                            </div>
                        </div>
                    <?php endif; ?>
                    <input type="file" name="thumbnail" class="form-control" accept="image/*">
                    <small class="text-muted">Leave empty to keep current</small>
                </div>

                <!-- Additional images (full URLs used directly) -->
                <div class="col-md-6 mb-3">
                    <label class="form-label">Additional Images</label>
                    <?php if ($existingImages): ?>
                        <div class="d-flex flex-wrap gap-2 mb-2">
                            <?php foreach ($existingImages as $img): ?>
                                <div class="position-relative">
                                    <img src="<?= htmlspecialchars($img['image_url']) ?>" width="80" class="rounded border">
                                    <div class="form-check position-absolute top-0 end-0 bg-white p-1 rounded">
                                        <input class="form-check-input" type="checkbox" name="remove_images[]" value="<?= $img['id'] ?>">
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                        <small class="text-muted">Check to delete individual images. Upload new ones below.</small>
                    <?php endif; ?>
                    <input type="file" name="images[]" class="form-control mt-2" accept="image/*" multiple>
                </div>
            </div>

            <button type="submit" class="btn btn-primary"><i class="bi bi-save"></i> Update Product</button>
            <a href="products.php" class="btn btn-secondary">Cancel</a>
        </form>
    </div>
</div>

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