<?php
require __DIR__ . '/_auth.php';
require_admin();
$pdo = db();
$title = 'Products';

function admin_slug($text)
{
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
    $text = trim((string) $text, '-');
    return $text !== '' ? $text : 'product-' . date('YmdHis');
}

function admin_lines_to_array($text)
{
    $lines = preg_split('/\r\n|\r|\n/', (string) $text);
    $items = array();
    foreach ($lines as $line) {
        $line = trim($line);
        if ($line !== '') {
            $items[] = $line;
        }
    }
    return $items;
}

function admin_swatches_to_array($text)
{
    $lines = admin_lines_to_array($text);
    $items = array();
    foreach ($lines as $line) {
        $parts = explode('|', $line, 2);
        $label = trim($parts[0]);
        $hex = isset($parts[1]) ? trim($parts[1]) : '#d8c8b1';
        if ($label !== '') {
            $items[] = array('label' => $label, 'hex' => $hex);
        }
    }
    return $items;
}

function admin_array_to_lines($items)
{
    if (!is_array($items)) {
        return '';
    }
    return implode("\n", $items);
}

function admin_swatches_to_lines($items)
{
    if (!is_array($items)) {
        return '';
    }
    $lines = array();
    foreach ($items as $item) {
        if (is_array($item)) {
            $lines[] = array_get($item, 'label', '') . '|' . array_get($item, 'hex', '');
        }
    }
    return implode("\n", $lines);
}

function admin_upload_file($field, $targetDir, $allowedExtensions)
{
    if (empty($_FILES[$field]) || !is_array($_FILES[$field]) || (int) $_FILES[$field]['error'] === UPLOAD_ERR_NO_FILE) {
        return '';
    }

    if ((int) $_FILES[$field]['error'] !== UPLOAD_ERR_OK) {
        return '';
    }

    $original = basename((string) $_FILES[$field]['name']);
    $ext = strtolower(pathinfo($original, PATHINFO_EXTENSION));
    if (!in_array($ext, $allowedExtensions, true)) {
        return '';
    }

    $safeName = admin_slug(pathinfo($original, PATHINFO_FILENAME)) . '-' . date('YmdHis') . '.' . $ext;
    $fullDir = __DIR__ . '/../' . trim($targetDir, '/');
    if (!is_dir($fullDir)) {
        mkdir($fullDir, 0775, true);
    }

    $destination = $fullDir . '/' . $safeName;
    if (!move_uploaded_file($_FILES[$field]['tmp_name'], $destination)) {
        return '';
    }

    return trim($targetDir, '/') . '/' . $safeName;
}

$action = isset($_GET['action']) ? $_GET['action'] : 'list';
$id = isset($_GET['id']) ? trim((string) $_GET['id']) : '';
$errors = array();
$notice = '';

if (!$pdo) {
    require __DIR__ . '/_header.php';
    ?>
    <div class="admin-card p-4">
        <h1 class="h4">MySQL setup required</h1>
        <p>Product admin needs MySQL. Import <code>database/schema.sql</code>, then edit <code>data/database.php</code>.</p>
    </div>
    <?php
    require __DIR__ . '/_footer.php';
    exit;
}

$blank = array(
    'id' => '', 'name' => '', 'tagline' => '', 'collection' => '', 'room' => '', 'price' => '0', 'compare_at' => '0',
    'rating' => '4.8', 'reviews' => '0', 'stock_status' => 'Made to order', 'seats' => '', 'dimensions' => '',
    'width_cm' => '0', 'depth_cm' => '0', 'height_cm' => '0', 'material' => '', 'color' => '', 'lead_time' => '',
    'warranty' => '', 'image' => '', 'model' => '', 'ar_floor_offset_cm' => '0', 'badges_json' => '[]',
    'features_json' => '[]', 'swatches_json' => '[]', 'is_active' => '1', 'sort_order' => '100'
);
$product = $blank;

if ($action === 'edit' && $id !== '') {
    $stmt = $pdo->prepare('SELECT * FROM products WHERE id = ? LIMIT 1');
    $stmt->execute(array($id));
    $found = $stmt->fetch();
    if ($found) {
        $product = array_merge($product, $found);
    } else {
        admin_redirect('products.php');
    }
}

if (($action === 'add' || $action === 'edit') && $_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf_token((string) (isset($_POST['csrf_token']) ? $_POST['csrf_token'] : ''))) {
        $errors[] = 'Security token expired. Please submit again.';
    }

    $postedId = admin_slug((string) (isset($_POST['id']) ? $_POST['id'] : ''));
    $name = clean_text((string) (isset($_POST['name']) ? $_POST['name'] : ''), 180);
    if ($name === '') {
        $errors[] = 'Product name is required.';
    }
    if ($postedId === '') {
        $postedId = admin_slug($name);
    }

    $imageUpload = admin_upload_file('image_file', 'assets/images/uploads', array('jpg', 'jpeg', 'png', 'webp'));
    $modelUpload = admin_upload_file('model_file', 'assets/models/uploads', array('glb', 'gltf', 'usdz'));

    $width = (float) (isset($_POST['width_cm']) ? $_POST['width_cm'] : 0);
    $depth = (float) (isset($_POST['depth_cm']) ? $_POST['depth_cm'] : 0);
    $height = (float) (isset($_POST['height_cm']) ? $_POST['height_cm'] : 0);
    $dimensions = clean_text((string) (isset($_POST['dimensions']) ? $_POST['dimensions'] : ''), 120);
    if ($dimensions === '' && ($width || $depth || $height)) {
        $dimensions = number_format($width, 0) . 'cm W x ' . number_format($depth, 0) . 'cm D x ' . number_format($height, 0) . 'cm H';
    }

    $image = $imageUpload !== '' ? $imageUpload : clean_text((string) (isset($_POST['image']) ? $_POST['image'] : ''), 255);
    $model = $modelUpload !== '' ? $modelUpload : clean_text((string) (isset($_POST['model']) ? $_POST['model'] : ''), 255);

    if ($image === '') {
        $errors[] = 'Product image is required.';
    }

    if (!$errors) {
        $values = array(
            'id' => $postedId,
            'name' => $name,
            'tagline' => clean_text((string) (isset($_POST['tagline']) ? $_POST['tagline'] : ''), 500),
            'collection' => clean_text((string) (isset($_POST['collection']) ? $_POST['collection'] : ''), 80),
            'room' => clean_text((string) (isset($_POST['room']) ? $_POST['room'] : ''), 120),
            'price' => (float) (isset($_POST['price']) ? $_POST['price'] : 0),
            'compare_at' => (float) (isset($_POST['compare_at']) ? $_POST['compare_at'] : 0),
            'rating' => (float) (isset($_POST['rating']) ? $_POST['rating'] : 0),
            'reviews' => (int) (isset($_POST['reviews']) ? $_POST['reviews'] : 0),
            'stock_status' => clean_text((string) (isset($_POST['stock_status']) ? $_POST['stock_status'] : ''), 80),
            'seats' => clean_text((string) (isset($_POST['seats']) ? $_POST['seats'] : ''), 80),
            'dimensions' => $dimensions,
            'width_cm' => $width,
            'depth_cm' => $depth,
            'height_cm' => $height,
            'material' => clean_text((string) (isset($_POST['material']) ? $_POST['material'] : ''), 220),
            'color' => clean_text((string) (isset($_POST['color']) ? $_POST['color'] : ''), 120),
            'lead_time' => clean_text((string) (isset($_POST['lead_time']) ? $_POST['lead_time'] : ''), 80),
            'warranty' => clean_text((string) (isset($_POST['warranty']) ? $_POST['warranty'] : ''), 160),
            'image' => $image,
            'model' => $model,
            'ar_floor_offset_cm' => (float) (isset($_POST['ar_floor_offset_cm']) ? $_POST['ar_floor_offset_cm'] : 0),
            'badges_json' => json_encode(admin_lines_to_array((string) (isset($_POST['badges']) ? $_POST['badges'] : '')), JSON_UNESCAPED_SLASHES),
            'features_json' => json_encode(admin_lines_to_array((string) (isset($_POST['features']) ? $_POST['features'] : '')), JSON_UNESCAPED_SLASHES),
            'swatches_json' => json_encode(admin_swatches_to_array((string) (isset($_POST['swatches']) ? $_POST['swatches'] : '')), JSON_UNESCAPED_SLASHES),
            'is_active' => !empty($_POST['is_active']) ? 1 : 0,
            'sort_order' => (int) (isset($_POST['sort_order']) ? $_POST['sort_order'] : 100),
        );

        if ($action === 'add') {
            $stmt = $pdo->prepare('INSERT INTO products (id, name, tagline, collection, room, price, compare_at, rating, reviews, stock_status, seats, dimensions, width_cm, depth_cm, height_cm, material, color, lead_time, warranty, image, model, ar_floor_offset_cm, badges_json, features_json, swatches_json, is_active, sort_order, created_at) VALUES (:id, :name, :tagline, :collection, :room, :price, :compare_at, :rating, :reviews, :stock_status, :seats, :dimensions, :width_cm, :depth_cm, :height_cm, :material, :color, :lead_time, :warranty, :image, :model, :ar_floor_offset_cm, :badges_json, :features_json, :swatches_json, :is_active, :sort_order, NOW())');
        } else {
            $values['old_id'] = $id;
            $stmt = $pdo->prepare('UPDATE products SET id=:id, name=:name, tagline=:tagline, collection=:collection, room=:room, price=:price, compare_at=:compare_at, rating=:rating, reviews=:reviews, stock_status=:stock_status, seats=:seats, dimensions=:dimensions, width_cm=:width_cm, depth_cm=:depth_cm, height_cm=:height_cm, material=:material, color=:color, lead_time=:lead_time, warranty=:warranty, image=:image, model=:model, ar_floor_offset_cm=:ar_floor_offset_cm, badges_json=:badges_json, features_json=:features_json, swatches_json=:swatches_json, is_active=:is_active, sort_order=:sort_order WHERE id=:old_id');
        }

        try {
            $stmt->execute($values);
            admin_redirect('products.php?saved=1');
        } catch (Exception $e) {
            $errors[] = 'Unable to save product. Product ID may already exist.';
        }
    }

    $product = array_merge($product, isset($values) ? $values : array());
}

if ($action === 'add' || $action === 'edit') {
    $badges = isset($_POST['badges']) ? (string) $_POST['badges'] : admin_array_to_lines(decode_json_array(array_get($product, 'badges_json', '[]')));
    $features = isset($_POST['features']) ? (string) $_POST['features'] : admin_array_to_lines(decode_json_array(array_get($product, 'features_json', '[]')));
    $swatches = isset($_POST['swatches']) ? (string) $_POST['swatches'] : admin_swatches_to_lines(decode_json_array(array_get($product, 'swatches_json', '[]')));
    require __DIR__ . '/_header.php';
    ?>
    <div class="admin-card p-4">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h4 mb-1"><?= $action === 'add' ? 'Add Sofa' : 'Edit Sofa' ?></h1>
                <p class="admin-muted mb-0">Upload product photo and GLB model, then set actual dimensions for AR.</p>
            </div>
            <a href="products.php" class="btn btn-outline-primary">Back</a>
        </div>

        <?php foreach ($errors as $error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endforeach; ?>

        <form method="post" enctype="multipart/form-data" class="row g-3">
            <input type="hidden" name="csrf_token" value="<?= e(csrf_token()) ?>">
            <div class="col-md-4"><label class="form-label">Product ID / slug</label><input class="form-control" name="id" value="<?= e(array_get($product, 'id')) ?>" placeholder="new-sofa-model"></div>
            <div class="col-md-8"><label class="form-label">Name</label><input class="form-control" name="name" required value="<?= e(array_get($product, 'name')) ?>"></div>
            <div class="col-12"><label class="form-label">Tagline</label><textarea class="form-control" name="tagline" rows="2"><?= e(array_get($product, 'tagline')) ?></textarea></div>

            <div class="col-md-3"><label class="form-label">Collection</label><input class="form-control" name="collection" value="<?= e(array_get($product, 'collection')) ?>"></div>
            <div class="col-md-3"><label class="form-label">Room</label><input class="form-control" name="room" value="<?= e(array_get($product, 'room')) ?>"></div>
            <div class="col-md-3"><label class="form-label">Price</label><input class="form-control" type="number" step="0.01" name="price" value="<?= e(array_get($product, 'price')) ?>"></div>
            <div class="col-md-3"><label class="form-label">Compare at</label><input class="form-control" type="number" step="0.01" name="compare_at" value="<?= e(array_get($product, 'compare_at')) ?>"></div>

            <div class="col-md-3"><label class="form-label">Width cm</label><input class="form-control" type="number" step="0.01" name="width_cm" value="<?= e(array_get($product, 'width_cm')) ?>"></div>
            <div class="col-md-3"><label class="form-label">Depth cm</label><input class="form-control" type="number" step="0.01" name="depth_cm" value="<?= e(array_get($product, 'depth_cm')) ?>"></div>
            <div class="col-md-3"><label class="form-label">Height cm</label><input class="form-control" type="number" step="0.01" name="height_cm" value="<?= e(array_get($product, 'height_cm')) ?>"></div>
            <div class="col-md-3"><label class="form-label">AR floor offset cm</label><input class="form-control" type="number" step="0.01" name="ar_floor_offset_cm" value="<?= e(array_get($product, 'ar_floor_offset_cm')) ?>"></div>
            <div class="col-md-6"><label class="form-label">Dimensions text</label><input class="form-control" name="dimensions" value="<?= e(array_get($product, 'dimensions')) ?>" placeholder="auto if blank"></div>
            <div class="col-md-3"><label class="form-label">Seats</label><input class="form-control" name="seats" value="<?= e(array_get($product, 'seats')) ?>"></div>
            <div class="col-md-3"><label class="form-label">Stock status</label><input class="form-control" name="stock_status" value="<?= e(array_get($product, 'stock_status')) ?>"></div>

            <div class="col-md-4"><label class="form-label">Material</label><input class="form-control" name="material" value="<?= e(array_get($product, 'material')) ?>"></div>
            <div class="col-md-4"><label class="form-label">Color</label><input class="form-control" name="color" value="<?= e(array_get($product, 'color')) ?>"></div>
            <div class="col-md-2"><label class="form-label">Rating</label><input class="form-control" type="number" step="0.1" name="rating" value="<?= e(array_get($product, 'rating')) ?>"></div>
            <div class="col-md-2"><label class="form-label">Reviews</label><input class="form-control" type="number" name="reviews" value="<?= e(array_get($product, 'reviews')) ?>"></div>

            <div class="col-md-4"><label class="form-label">Lead time</label><input class="form-control" name="lead_time" value="<?= e(array_get($product, 'lead_time')) ?>"></div>
            <div class="col-md-4"><label class="form-label">Warranty</label><input class="form-control" name="warranty" value="<?= e(array_get($product, 'warranty')) ?>"></div>
            <div class="col-md-4"><label class="form-label">Sort order</label><input class="form-control" type="number" name="sort_order" value="<?= e(array_get($product, 'sort_order')) ?>"></div>

            <div class="col-md-6"><label class="form-label">Image path</label><input class="form-control" name="image" value="<?= e(array_get($product, 'image')) ?>"><input class="form-control mt-2" type="file" name="image_file" accept=".jpg,.jpeg,.png,.webp"></div>
            <div class="col-md-6"><label class="form-label">3D model path</label><input class="form-control" name="model" value="<?= e(array_get($product, 'model')) ?>"><input class="form-control mt-2" type="file" name="model_file" accept=".glb,.gltf,.usdz"></div>

            <div class="col-md-4"><label class="form-label">Badges</label><textarea class="form-control" name="badges" rows="5" placeholder="Best seller&#10;AR-ready"><?= e($badges) ?></textarea></div>
            <div class="col-md-4"><label class="form-label">Features</label><textarea class="form-control" name="features" rows="5"><?= e($features) ?></textarea></div>
            <div class="col-md-4"><label class="form-label">Swatches</label><textarea class="form-control" name="swatches" rows="5" placeholder="Moss|#55736c"><?= e($swatches) ?></textarea></div>

            <div class="col-12 form-check ms-2"><input class="form-check-input" type="checkbox" name="is_active" value="1" id="is_active" <?= array_get($product, 'is_active', 1) ? 'checked' : '' ?>><label class="form-check-label" for="is_active">Active / visible in store</label></div>
            <div class="col-12"><button class="btn btn-primary btn-lg" type="submit">Save Product</button></div>
        </form>
    </div>
    <?php
    require __DIR__ . '/_footer.php';
    exit;
}

if (isset($_GET['saved'])) {
    $notice = 'Product saved successfully.';
}

$stmt = $pdo->query('SELECT * FROM products ORDER BY sort_order ASC, created_at DESC');
$products = $stmt->fetchAll();
require __DIR__ . '/_header.php';
?>
<div class="admin-card p-4">
    <div class="d-flex flex-wrap gap-2 justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h4 mb-1">Products</h1>
            <p class="admin-muted mb-0">Add, edit, hide, and upload AR sofa models.</p>
        </div>
        <a href="products.php?action=add" class="btn btn-primary"><i class="bi bi-plus-lg"></i> Add Sofa</a>
    </div>
    <?php if ($notice): ?><div class="alert alert-success"><?= e($notice) ?></div><?php endif; ?>
    <div class="table-responsive">
        <table class="table align-middle admin-table">
            <thead><tr><th>Image</th><th>Name</th><th>Collection</th><th>Price</th><th>AR Model</th><th>Status</th><th></th></tr></thead>
            <tbody>
            <?php foreach ($products as $item): ?>
                <tr>
                    <td><?php if (array_get($item, 'image')): ?><img src="../<?= e($item['image']) ?>" alt=""><?php endif; ?></td>
                    <td><strong><?= e($item['name']) ?></strong><br><span class="admin-muted small"><?= e($item['id']) ?></span></td>
                    <td><?= e($item['collection']) ?></td>
                    <td><?= money($item['price']) ?></td>
                    <td><?= array_get($item, 'model') ? '<span class="badge badge-soft">GLB/AR</span>' : '<span class="text-muted">None</span>' ?></td>
                    <td><?= (int) $item['is_active'] ? '<span class="badge text-bg-success">Active</span>' : '<span class="badge text-bg-secondary">Hidden</span>' ?></td>
                    <td class="text-end">
                        <a href="products.php?action=edit&id=<?= e($item['id']) ?>" class="btn btn-sm btn-outline-primary">Edit</a>
                        <a href="product-delete.php?id=<?= e($item['id']) ?>&csrf_token=<?= e(csrf_token()) ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Delete this product?')">Delete</a>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$products): ?><tr><td colspan="7" class="text-center admin-muted py-5">No products yet.</td></tr><?php endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php require __DIR__ . '/_footer.php'; ?>
