<?php
declare(strict_types=1);

use App\Core\Auth;
use App\Core\Database;
use App\Core\ModuleCrud;
use App\Core\Security;
use App\Core\SmartForm;

$pageTitle = 'Products | Vendor';
$errors = [];
$editingId = max(0, (int)($_GET['edit'] ?? $_POST['id'] ?? 0));
$editing = $editingId ? Database::safeFetchOne('SELECT * FROM products WHERE id=? AND vendor_id=? AND status<>"deleted" LIMIT 1', [$editingId, $vendorId]) : null;
if ($editingId && !$editing) {
    $errors[] = 'Product not found or not owned by this vendor.';
    $editingId = 0;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verify_csrf()) {
        $errors[] = 'Invalid security token. Refresh the page and try again.';
    } else {
        $action = (string)($_POST['_action'] ?? 'save');
        try {
            if ($action === 'delete') {
                $id = max(0, (int)($_POST['id'] ?? 0));
                if (!Database::safeFetchOne('SELECT id FROM products WHERE id=? AND vendor_id=? LIMIT 1', [$id, $vendorId])) throw new RuntimeException('Product not found.');
                Database::execute('UPDATE products SET status="deleted",updated_at=NOW() WHERE id=? AND vendor_id=?', [$id, $vendorId]);
                Security::logActivity(Auth::id(), 'vendor_product_deleted', ['product_id' => $id, 'vendor_id' => $vendorId]);
                set_flash('success', 'Product removed successfully.');
                redirect('vendor/products.php');
            }

            $id = max(0, (int)($_POST['id'] ?? 0));
            $existing = $id ? Database::safeFetchOne('SELECT * FROM products WHERE id=? AND vendor_id=? LIMIT 1', [$id, $vendorId]) : null;
            if ($id && !$existing) throw new RuntimeException('Product not found.');

            $_POST['vendor_id'] = (string)$vendorId;
            $_POST['status'] = $existing && ($existing['status'] ?? '') === 'published'
                ? (($_POST['vendor_status'] ?? 'published') === 'disabled' ? 'disabled' : 'published')
                : 'pending';
            foreach (['is_featured','is_trending','is_best_selling'] as $protected) $_POST[$protected] = (string)($existing[$protected] ?? 0);
            $payload = SmartForm::prepare('products', $_POST, $_FILES, $id ?: null, $existing);
            if ((float)($payload['regular_price'] ?? 0) <= 0) throw new RuntimeException('Regular price must be greater than zero.');
            if ((float)($payload['sale_price'] ?? 0) > (float)($payload['regular_price'] ?? 0)) throw new RuntimeException('Sale price cannot be greater than regular price.');

            Database::transaction(function () use ($payload, $id, $vendorId, &$editingId): void {
                if (!ModuleCrud::save('products', $payload, $id ?: null)) throw new RuntimeException('Could not save the product.');
                $productId = $id ?: Database::lastInsertId();
                $editingId = $productId;

                $removeIds = array_values(array_filter(array_map('intval', (array)($_POST['remove_gallery'] ?? []))));
                foreach ($removeIds as $imageId) {
                    $row = Database::safeFetchOne('SELECT pi.image_path FROM product_images pi JOIN products p ON p.id=pi.product_id WHERE pi.id=? AND pi.product_id=? AND p.vendor_id=? LIMIT 1', [$imageId, $productId, $vendorId]);
                    if (!$row) continue;
                    Database::execute('DELETE FROM product_images WHERE id=? AND product_id=?', [$imageId, $productId]);
                    SmartForm::removeFile((string)$row['image_path']);
                }

                $currentCount = (int)(Database::safeFetchOne('SELECT COUNT(*) total FROM product_images WHERE product_id=?', [$productId])['total'] ?? 0);
                foreach (SmartForm::normalizeFiles($_FILES['gallery_images'] ?? []) as $file) {
                    if ((int)($file['error'] ?? UPLOAD_ERR_NO_FILE) === UPLOAD_ERR_NO_FILE) continue;
                    if ($currentCount >= 12) throw new RuntimeException('A product can have a maximum of 12 gallery images.');
                    $path = SmartForm::storeFile('products', 'gallery_image', $file, true);
                    Database::execute('INSERT INTO product_images (product_id,image_path,sort_order) VALUES (?,?,?)', [$productId, $path, $currentCount]);
                    $currentCount++;
                }
            });

            Security::logActivity(Auth::id(), $id ? 'vendor_product_updated' : 'vendor_product_created', ['product_id' => $editingId, 'vendor_id' => $vendorId]);
            set_flash('success', $id ? 'Product updated successfully.' : 'Product submitted for approval.');
            redirect('vendor/products.php?edit=' . $editingId . '#productForm');
        } catch (Throwable $exception) {
            $errors[] = $exception->getMessage();
            $editing = array_merge($editing ?? [], $_POST);
            $editingId = max(0, (int)($_POST['id'] ?? 0));
        }
    }
}

$categories = Database::safeFetchAll('SELECT id,parent_id,name FROM categories WHERE status="active" ORDER BY parent_id,sort_order,name');
$brands = Database::safeFetchAll('SELECT id,name FROM brands WHERE status="active" ORDER BY name');
$gallery = $editingId ? Database::safeFetchAll('SELECT id,image_path,sort_order FROM product_images WHERE product_id=? ORDER BY sort_order,id', [$editingId]) : [];
$query = mb_substr(trim((string)($_GET['q'] ?? '')), 0, 100);
$params = [$vendorId];
$where = 'p.vendor_id=? AND p.status<>"deleted"';
if ($query !== '') {
    $where .= ' AND (p.name LIKE ? OR p.sku LIKE ? OR p.barcode LIKE ? OR p.product_code LIKE ?)';
    $like = '%' . $query . '%';
    array_push($params, $like, $like, $like, $like);
}
$products = Database::safeFetchAll('SELECT p.*,c.name category_name,b.name brand_name FROM products p LEFT JOIN categories c ON c.id=p.category_id LEFT JOIN brands b ON b.id=p.brand_id WHERE ' . $where . ' ORDER BY p.id DESC LIMIT 100', $params);
$productCount = db_count('products', 'vendor_id=? AND status<>"deleted"', [$vendorId]);
$orderCount = db_count('order_items', 'vendor_id=?', [$vendorId]);
$sales = (float)(Database::safeFetchOne('SELECT COALESCE(SUM(total_price),0) total FROM order_items WHERE vendor_id=?', [$vendorId])['total'] ?? 0);
$wallet = App\Core\WalletService::balance((int)$vendor['user_id'], 'cash');
$form = static fn(string $key, mixed $default = ''): mixed => $editing[$key] ?? $default;
$imageUrl = static function (string $path): string {
    if ($path === '') return asset('images/gallery/product-images/01.png');
    if (preg_match('#^https?://#i', $path)) return $path;
    if (str_starts_with($path, 'public/')) return url($path);
    if (str_starts_with($path, 'uploads/')) return url('public/' . $path);
    if (str_starts_with($path, 'assets/')) return url('public/' . $path);
    return url(ltrim($path, '/'));
};

require ROOT_PATH . '/app/Layouts/panel_header.php';
?>
<link rel="stylesheet" href="<?= admin_asset('css/smart-forms.css') ?>">
<div class="d-flex flex-wrap gap-3 align-items-start justify-content-between mb-4"><div><h1 class="h3 mb-1">Products</h1><p class="text-muted mb-0">Manage product information, pricing, images, SEO and stock for <?= e($vendor['shop_name']) ?>.</p></div><a class="btn btn-primary" href="<?= url('vendor/product-create.php#productForm') ?>">Add product</a></div>
<?php if ($message = flash('success')): ?><div class="alert alert-success"><?= e($message) ?></div><?php endif; ?>
<?php foreach ($errors as $error): ?><div class="alert alert-danger"><?= e($error) ?></div><?php endforeach; ?>
<div class="row g-3 mb-4"><div class="col-6 col-xl-3"><div class="stat-tile"><small>Products</small><strong><?= number_format($productCount) ?></strong></div></div><div class="col-6 col-xl-3"><div class="stat-tile"><small>Order items</small><strong><?= number_format($orderCount) ?></strong></div></div><div class="col-6 col-xl-3"><div class="stat-tile"><small>Gross sales</small><strong><?= money($sales) ?></strong></div></div><div class="col-6 col-xl-3"><div class="stat-tile"><small>Cash wallet</small><strong><?= money($wallet) ?></strong></div></div></div>

<div class="card module-card smart-form-card mb-4" id="productForm"><div class="card-header bg-white d-flex justify-content-between"><div><strong><?= $editingId ? 'Edit product #' . $editingId : 'Add product' ?></strong><div class="small text-muted">New products are submitted for administrator approval.</div></div><?php if ($editingId): ?><a class="btn btn-sm btn-outline-secondary" href="<?= url('vendor/product-create.php#productForm') ?>">Create another</a><?php endif; ?></div><div class="card-body">
<form method="post" enctype="multipart/form-data" class="smart-form" data-smart-form data-entity="products">
<?= csrf_field() ?><input type="hidden" name="_action" value="save"><input type="hidden" name="id" value="<?= (int)$editingId ?>">
<section class="smart-form-section"><div class="smart-form-section-heading"><span>Product identity</span></div><div class="row g-3">
<div class="col-lg-6"><label class="form-label required-label">Product name</label><input class="form-control" name="name" value="<?= e($form('name')) ?>" required></div>
<div class="col-lg-3"><label class="form-label required-label">Category</label><select class="form-select" name="category_id" required><option value="">Select category</option><?php foreach ($categories as $category): ?><option value="<?= (int)$category['id'] ?>" <?= (int)$form('category_id') === (int)$category['id'] ? 'selected' : '' ?>><?= $category['parent_id'] ? '↳ ' : '' ?><?= e($category['name']) ?></option><?php endforeach; ?></select></div>
<div class="col-lg-3"><label class="form-label">Brand</label><select class="form-select" name="brand_id"><option value="">No brand</option><?php foreach ($brands as $brand): ?><option value="<?= (int)$brand['id'] ?>" <?= (int)$form('brand_id') === (int)$brand['id'] ? 'selected' : '' ?>><?= e($brand['name']) ?></option><?php endforeach; ?></select></div>
<div class="col-lg-8"><label class="form-label">Slug</label><input class="form-control" name="slug" id="sf_vendor_slug" data-auto="slug" value="<?= e($form('slug')) ?>"><div class="form-check mt-1"><input class="form-check-input smart-auto-toggle" type="checkbox" data-target="sf_vendor_slug" id="auto_vendor_slug" checked><label class="form-check-label small text-muted" for="auto_vendor_slug">Automatically update from name</label></div></div>
<div class="col-lg-4"><label class="form-label">Product type</label><select class="form-select" name="product_type"><option value="physical" <?= $form('product_type','physical') === 'physical' ? 'selected' : '' ?>>Physical</option><option value="digital" <?= $form('product_type') === 'digital' ? 'selected' : '' ?>>Digital</option></select></div>
<div class="col-lg-4"><label class="form-label">SKU</label><div class="input-group"><input class="form-control" name="sku" id="vendor_sku" data-auto="code" value="<?= e($form('sku')) ?>"><button class="btn btn-outline-secondary smart-generate-code" type="button" data-target="vendor_sku" data-field="sku">Generate</button></div></div>
<div class="col-lg-4"><label class="form-label">Barcode</label><div class="input-group"><input class="form-control" name="barcode" id="vendor_barcode" data-auto="code" value="<?= e($form('barcode')) ?>"><button class="btn btn-outline-secondary smart-generate-code" type="button" data-target="vendor_barcode" data-field="barcode">Generate</button></div></div>
<div class="col-lg-4"><label class="form-label">Product code</label><div class="input-group"><input class="form-control" name="product_code" id="vendor_product_code" data-auto="code" value="<?= e($form('product_code')) ?>"><button class="btn btn-outline-secondary smart-generate-code" type="button" data-target="vendor_product_code" data-field="product_code">Generate</button></div></div>
</div></section>
<section class="smart-form-section"><div class="smart-form-section-heading"><span>Price, stock & delivery</span></div><div class="row g-3">
<?php foreach ([['purchase_price','Purchase price'],['regular_price','Regular price'],['sale_price','Sale price'],['flash_price','Flash price'],['stock','Stock'],['weight','Weight'],['reward_points','Reward points'],['shipping_charge','Shipping charge']] as [$field,$label]): ?><div class="col-6 col-lg-3"><label class="form-label <?= $field === 'regular_price' ? 'required-label' : '' ?>"><?= e($label) ?></label><input class="form-control" type="number" min="0" step="<?= in_array($field,['stock','reward_points'],true) ? '1' : '0.01' ?>" name="<?= e($field) ?>" value="<?= e($form($field,0)) ?>" <?= $field === 'regular_price' ? 'required' : '' ?>></div><?php endforeach; ?>
</div></section>
<section class="smart-form-section"><div class="smart-form-section-heading"><span>Images & media</span></div><div class="row g-3">
<div class="col-lg-6"><label class="form-label">Default image</label><div class="smart-upload-box"><img class="smart-image-preview" id="vendor_image_preview" src="<?= e($imageUrl((string)$form('image'))) ?>" alt=""><div class="flex-grow-1"><input class="form-control" type="file" name="image" accept="image/jpeg,image/png,image/webp" data-preview="vendor_image_preview"><div class="form-text">JPG, PNG or WEBP. Recommended square image.</div><?php if ($form('image')): ?><div class="form-check mt-2"><input class="form-check-input" type="checkbox" name="remove_image" value="1" id="vendor_remove_image"><label class="form-check-label text-danger" for="vendor_remove_image">Remove current image</label></div><?php endif; ?></div></div></div>
<div class="col-lg-6"><label class="form-label">OG image</label><div class="smart-upload-box"><img class="smart-image-preview" id="vendor_og_preview" src="<?= e($imageUrl((string)($form('og_image') ?: $form('image')))) ?>" alt=""><div class="flex-grow-1"><input class="form-control" type="file" name="og_image" accept="image/jpeg,image/png,image/webp" data-preview="vendor_og_preview"><div class="form-text">Social preview for Facebook, WhatsApp and Messenger. Recommended 1200 × 630.</div><?php if ($form('og_image')): ?><div class="form-check mt-2"><input class="form-check-input" type="checkbox" name="remove_og_image" value="1" id="vendor_remove_og"><label class="form-check-label text-danger" for="vendor_remove_og">Remove current OG image</label></div><?php endif; ?></div></div></div>
<div class="col-12"><label class="form-label">Gallery images</label><input class="form-control" type="file" name="gallery_images[]" accept="image/jpeg,image/png,image/webp" multiple><div class="form-text">Upload up to 12 images in total.</div><div class="d-flex flex-wrap gap-2 mt-3"><?php foreach ($gallery as $image): ?><label class="border rounded p-2 text-center"><img src="<?= e($imageUrl((string)$image['image_path'])) ?>" width="100" height="80" style="object-fit:cover" class="rounded d-block mb-1" alt=""><input type="checkbox" name="remove_gallery[]" value="<?= (int)$image['id'] ?>"> <span class="small text-danger">Remove</span></label><?php endforeach; ?></div></div>
<div class="col-12"><label class="form-label">Video URL</label><input class="form-control" type="url" name="video_url" value="<?= e($form('video_url')) ?>" placeholder="https://youtube.com/..."></div>
</div></section>
<section class="smart-form-section"><div class="smart-form-section-heading"><span>Descriptions</span></div><div class="row g-3">
<?php foreach ([['short_description','Short description'],['description','Detailed description']] as [$field,$label]): ?><div class="col-12"><label class="form-label"><?= e($label) ?></label><input type="hidden" name="<?= e($field) ?>" id="vendor_<?= e($field) ?>" value="<?= e($form($field)) ?>"><div class="smart-editor-toolbar" data-editor-toolbar="vendor_<?= e($field) ?>_editor"></div><div class="smart-rich-editor" id="vendor_<?= e($field) ?>_editor" contenteditable="true" data-target="vendor_<?= e($field) ?>"><?= sanitize_rich_html((string)$form($field)) ?></div></div><?php endforeach; ?>
</div></section>
<section class="smart-form-section"><div class="smart-form-section-heading"><span>SEO & status</span></div><div class="row g-3">
<div class="col-lg-6"><label class="form-label">Meta title</label><input class="form-control" name="meta_title" id="sf_vendor_meta_title" data-auto="meta-title" value="<?= e($form('meta_title')) ?>"></div>
<div class="col-lg-6"><label class="form-label">Vendor status</label><select class="form-select" name="vendor_status"><option value="pending">Pending approval</option><?php if (($form('status') ?? '') === 'published'): ?><option value="published" selected>Published</option><?php endif; ?><option value="disabled" <?= $form('status') === 'disabled' ? 'selected' : '' ?>>Disabled</option></select></div>
<div class="col-12"><label class="form-label">Meta description</label><textarea class="form-control" name="meta_description" rows="3"><?= e($form('meta_description')) ?></textarea></div>
<div class="col-12"><label class="form-label">Meta keywords</label><input class="form-control" name="meta_keywords" id="sf_vendor_meta_keywords" data-auto="meta-keywords" value="<?= e($form('meta_keywords')) ?>"><div class="d-flex flex-wrap gap-1 mt-2 smart-keyword-chips" data-target="sf_vendor_meta_keywords"></div></div>
</div></section>
<div class="smart-form-actions d-flex gap-2 justify-content-end"><?php if ($editingId): ?><a class="btn btn-outline-secondary btn-lg" href="<?= url('vendor/products.php') ?>">Cancel</a><?php endif; ?><button class="btn btn-primary btn-lg"><?= $editingId ? 'Update product' : 'Submit product' ?></button></div>
</form></div></div>

<div class="card module-card"><div class="card-header bg-white"><form class="d-flex flex-wrap gap-2"><input class="form-control" style="max-width:420px" name="q" value="<?= e($query) ?>" placeholder="Search product, SKU, barcode or code"><button class="btn btn-outline-primary">Search</button><?php if ($query): ?><a class="btn btn-outline-secondary" href="<?= url('vendor/products.php') ?>">Clear</a><?php endif; ?></form></div><div class="table-responsive"><table class="table align-middle mb-0"><thead><tr><th>Product</th><th>Category</th><th>Codes</th><th>Price</th><th>Stock</th><th>Status</th><th>Actions</th></tr></thead><tbody><?php if (!$products): ?><?= table_empty(7,'No products found.') ?><?php endif; ?><?php foreach ($products as $product): ?><tr><td><div class="d-flex gap-2 align-items-center"><img src="<?= e($imageUrl((string)$product['image'])) ?>" width="58" height="50" class="rounded border" style="object-fit:contain" alt=""><div><strong><?= e($product['name']) ?></strong><div class="small text-muted"><?= e($product['brand_name'] ?? 'No brand') ?></div></div></div></td><td><?= e($product['category_name'] ?? '—') ?></td><td><div class="small"><?= e($product['sku'] ?: '—') ?></div><div class="small text-muted"><?= e($product['barcode'] ?: $product['product_code']) ?></div></td><td><?= money((float)($product['sale_price'] ?: $product['regular_price'])) ?></td><td><?= (int)$product['stock'] ?></td><td><?= badge((string)$product['status']) ?></td><td class="text-nowrap"><a class="btn btn-sm btn-outline-primary" href="?edit=<?= (int)$product['id'] ?>#productForm">Edit</a> <form method="post" class="d-inline" onsubmit="return confirm('Remove this product?')"><?= csrf_field() ?><input type="hidden" name="_action" value="delete"><input type="hidden" name="id" value="<?= (int)$product['id'] ?>"><button class="btn btn-sm btn-outline-danger">Delete</button></form></td></tr><?php endforeach; ?></tbody></table></div></div>
<script src="<?= admin_asset('js/smart-forms.js') ?>"></script>
<?php require ROOT_PATH . '/app/Layouts/panel_footer.php'; ?>
