<?php
declare(strict_types=1);
require_once __DIR__ . '/../app/config/bootstrap.php';
require_once __DIR__ . '/../app/core/Auth.php';
require_once __DIR__ . '/../app/core/AdminLayout.php';
require_once __DIR__ . '/../app/models/Product.php';
require_once __DIR__ . '/../app/core/Csrf.php';
require_once __DIR__ . '/../app/core/MediaUpload.php';

Auth::requireAdmin();
$model = new Product();
$message = '';
$error = '';

function collectProductPost(bool $isEdit): array
{
    return [
        'sku' => trim((string)($_POST['sku'] ?? '')),
        'title' => trim((string)($_POST['title'] ?? '')),
        'slug' => trim((string)($_POST['slug'] ?? '')),
        'category' => trim((string)($_POST['category'] ?? '')),
        'brand' => trim((string)($_POST['brand'] ?? '')),
        'price' => (float)($_POST['price'] ?? 0),
        'short_description' => trim((string)($_POST['short_description'] ?? '')),
        'long_description' => trim((string)($_POST['long_description'] ?? '')),
        'discount_percent' => (int)($_POST['discount_percent'] ?? 0),
        'stock' => (int)($_POST['stock'] ?? 0),
        'weight_kg' => $_POST['weight_kg'] !== '' ? (float)$_POST['weight_kg'] : null,
        'dimensions' => trim((string)($_POST['dimensions'] ?? '')),
        'tags' => trim((string)($_POST['tags'] ?? '')),
        'status' => trim((string)($_POST['status'] ?? 'active')),
        'tracking_code' => trim((string)($_POST['tracking_code'] ?? '')),
    ];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && Csrf::validate($_POST['_csrf'] ?? null)) {
    $action = (string)($_POST['action'] ?? 'create');

    if ($action === 'delete_soft') {
        $id = (int)($_POST['id'] ?? 0);
        if ($id > 0 && $model->softDelete($id)) {
            $message = 'محصول به صورت نرم حذف شد.';
        } else {
            $error = 'حذف انجام نشد.';
        }
    } elseif ($action === 'delete_hard') {
        $id = (int)($_POST['id'] ?? 0);
        $row = $id > 0 ? $model->findAny($id) : null;
        if ($row) {
            MediaUpload::deletePublicPath($row['image_url'] ?? null);
            MediaUpload::deletePublicPath($row['video_path'] ?? null);
        }
        if ($id > 0 && $model->hardDelete($id)) {
            $message = 'محصول برای همیشه حذف شد.';
        } else {
            $error = 'حذف انجام نشد.';
        }
    } elseif ($action === 'save' || $action === 'create') {
        $data = collectProductPost($action === 'save');
        $id = (int)($_POST['id'] ?? 0);

        $imgPath = null;
        if (!empty($_FILES['image_file']['name']) && (int)($_FILES['image_file']['error'] ?? 0) !== UPLOAD_ERR_NO_FILE) {
            $up = MediaUpload::productImage($_FILES['image_file']);
            if (!$up['ok']) {
                $error = 'خطا در آپلود تصویر: ' . htmlspecialchars((string)($up['error'] ?? ''));
            } else {
                $imgPath = $up['path'] ?? null;
            }
        }
        $vidPath = null;
        if ($error === '' && !empty($_FILES['video_file']['name']) && (int)($_FILES['video_file']['error'] ?? 0) !== UPLOAD_ERR_NO_FILE) {
            $upv = MediaUpload::productVideo($_FILES['video_file']);
            if (!$upv['ok']) {
                $error = 'خطا در آپلود ویدیو: ' . htmlspecialchars((string)($upv['error'] ?? ''));
            } else {
                $vidPath = $upv['path'] ?? null;
            }
        }

        if ($error === '') {
            if ($data['sku'] === '' || $data['title'] === '' || $data['category'] === '') {
                $error = 'SKU، عنوان و دسته الزامی است.';
            } elseif ($action === 'save' && $id > 0) {
                $existing = $model->findAny($id);
                if (!$existing) {
                    $error = 'محصول یافت نشد.';
                } else {
                    if ($imgPath) {
                        MediaUpload::deletePublicPath((string)($existing['image_url'] ?? ''));
                    }
                    if ($vidPath) {
                        MediaUpload::deletePublicPath((string)($existing['video_path'] ?? ''));
                    }
                    $data['image_url'] = $imgPath ?: ($existing['image_url'] ?? '');
                    $data['video_path'] = $vidPath ?: ($existing['video_path'] ?? '');
                    if ($data['tracking_code'] === '') {
                        $data['tracking_code'] = (string)($existing['tracking_code'] ?? $model->ensureUniqueTracking());
                    }
                    if ($model->update($id, $data)) {
                        $message = 'محصول به‌روزرسانی شد.';
                    } else {
                        $error = 'ذخیره نشد.';
                    }
                }
            } else {
                $data['image_url'] = $imgPath ?? '';
                $data['video_path'] = $vidPath ?? '';
                if ($model->create($data)) {
                    $message = 'محصول جدید ثبت شد.';
                } else {
                    $error = 'ثبت محصول انجام نشد (احتمال تکراری بودن SKU یا اسلاگ).';
                }
            }
        }
    }
}

$editId = isset($_GET['edit']) ? (int)$_GET['edit'] : 0;
$editRow = $editId > 0 ? $model->findAny($editId) : null;
$products = $model->all(500, true);
?>
<!doctype html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="<?= htmlspecialchars(assetPath('/assets/css/admin.css')) ?>">
    <title>مدیریت محصولات</title>
</head>
<body>
<div class="admin-wrap">
    <?php renderAdminSidebar('products'); ?>
    <main class="content">
        <h1>مدیریت محصولات</h1>
        <?php if ($message): ?><p class="admin-flash ok"><?= htmlspecialchars($message) ?></p><?php endif; ?>
        <?php if ($error): ?><p class="admin-flash err"><?= $error ?></p><?php endif; ?>

        <h2><?= $editRow ? 'ویرایش محصول #' . (int)$editRow['id'] : 'افزودن محصول' ?></h2>
        <form class="admin-form" method="post" enctype="multipart/form-data">
            <input type="hidden" name="_csrf" value="<?= htmlspecialchars(Csrf::token()) ?>">
            <input type="hidden" name="action" value="<?= $editRow ? 'save' : 'create' ?>">
            <?php if ($editRow): ?><input type="hidden" name="id" value="<?= (int)$editRow['id'] ?>"><?php endif; ?>

            <label>SKU</label>
            <input name="sku" required value="<?= htmlspecialchars((string)($editRow['sku'] ?? '')) ?>">

            <label>شناسه پیگیری کالا (خالی = خودکار)</label>
            <input name="tracking_code" value="<?= htmlspecialchars((string)($editRow['tracking_code'] ?? '')) ?>" placeholder="مثال PRD-...">

            <label>عنوان</label>
            <input name="title" required value="<?= htmlspecialchars((string)($editRow['title'] ?? '')) ?>">

            <label>اسلاگ (خالی = خودکار از عنوان)</label>
            <input name="slug" value="<?= htmlspecialchars((string)($editRow['slug'] ?? '')) ?>">

            <label>دسته‌بندی</label>
            <input name="category" required value="<?= htmlspecialchars((string)($editRow['category'] ?? '')) ?>">

            <label>برند</label>
            <input name="brand" value="<?= htmlspecialchars((string)($editRow['brand'] ?? '')) ?>">

            <label>قیمت (تومان)</label>
            <input name="price" type="number" step="0.01" required value="<?= htmlspecialchars((string)($editRow['price'] ?? '')) ?>">

            <label>تخفیف ٪</label>
            <input name="discount_percent" type="number" value="<?= (int)($editRow['discount_percent'] ?? 0) ?>">

            <label>موجودی</label>
            <input name="stock" type="number" required value="<?= (int)($editRow['stock'] ?? 0) ?>">

            <label>وزن (کیلوگرم)</label>
            <input name="weight_kg" type="number" step="0.001" value="<?= htmlspecialchars((string)($editRow['weight_kg'] ?? '')) ?>">

            <label>ابعاد</label>
            <input name="dimensions" value="<?= htmlspecialchars((string)($editRow['dimensions'] ?? '')) ?>">

            <label>برچسب‌ها (با ویرگول)</label>
            <input name="tags" value="<?= htmlspecialchars((string)($editRow['tags'] ?? '')) ?>">

            <label>وضعیت</label>
            <select name="status">
                <?php $st = (string)($editRow['status'] ?? 'active'); ?>
                <option value="active" <?= $st === 'active' ? 'selected' : '' ?>>فعال</option>
                <option value="inactive" <?= $st === 'inactive' ? 'selected' : '' ?>>غیرفعال</option>
            </select>

            <label>توضیح کوتاه</label>
            <textarea name="short_description" rows="3"><?= htmlspecialchars((string)($editRow['short_description'] ?? '')) ?></textarea>

            <label>توضیح کامل</label>
            <textarea name="long_description" rows="6"><?= htmlspecialchars((string)($editRow['long_description'] ?? '')) ?></textarea>

            <label>تصویر شاخص — آپلود فایل (JPG/PNG/WebP)</label>
            <?php if (!empty($editRow['image_url'])): ?>
                <p>فعلی: <a href="<?= htmlspecialchars(appPath('/' . ltrim((string)$editRow['image_url'], '/'))) ?>" target="_blank">پیش‌نمایش</a></p>
            <?php endif; ?>
            <input type="file" name="image_file" accept="image/jpeg,image/png,image/webp">

            <label>ویدیو محصول — آپلود MP4/WebM</label>
            <?php if (!empty($editRow['video_path'])): ?>
                <p>فعلی: <a href="<?= htmlspecialchars(appPath('/' . ltrim((string)$editRow['video_path'], '/'))) ?>" target="_blank">فایل</a></p>
            <?php endif; ?>
            <input type="file" name="video_file" accept="video/mp4,video/webm">

            <button type="submit"><?= $editRow ? 'ذخیره تغییرات' : 'ثبت محصول' ?></button>
            <?php if ($editRow): ?>
                <a class="btn btn-secondary" href="<?= htmlspecialchars(appPath('/admin/products.php')) ?>">انصراف</a>
            <?php endif; ?>
        </form>

        <h2>فهرست محصولات</h2>
        <div class="admin-table-wrap">
            <table class="admin-table">
                <thead>
                <tr>
                    <th>#</th>
                    <th>شناسه پیگیری</th>
                    <th>عنوان</th>
                    <th>قیمت</th>
                    <th>موجودی</th>
                    <th>حذف نرم / سخت</th>
                    <th>ویرایش</th>
                </tr>
                </thead>
                <tbody>
                <?php foreach ($products as $p): ?>
                    <tr class="<?= !empty($p['deleted_at']) ? 'row-muted' : '' ?>">
                        <td><?= (int)$p['id'] ?></td>
                        <td><code><?= htmlspecialchars((string)($p['tracking_code'] ?? '-')) ?></code></td>
                        <td><?= htmlspecialchars((string)$p['title']) ?></td>
                        <td><?= number_format((float)$p['price']) ?></td>
                        <td><?= (int)$p['stock'] ?></td>
                        <td>
                            <?php if (empty($p['deleted_at'])): ?>
                                <form method="post" class="inline-form" onsubmit="return confirm('حذف نرم؟');">
                                    <input type="hidden" name="_csrf" value="<?= htmlspecialchars(Csrf::token()) ?>">
                                    <input type="hidden" name="action" value="delete_soft">
                                    <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                                    <button type="submit" class="btn-sm danger-soft">نرم</button>
                                </form>
                            <?php endif; ?>
                            <form method="post" class="inline-form" onsubmit="return confirm('حذف دائم؟');">
                                <input type="hidden" name="_csrf" value="<?= htmlspecialchars(Csrf::token()) ?>">
                                <input type="hidden" name="action" value="delete_hard">
                                <input type="hidden" name="id" value="<?= (int)$p['id'] ?>">
                                <button type="submit" class="btn-sm danger">دائم</button>
                            </form>
                        </td>
                        <td><a href="<?= htmlspecialchars(appPath('/admin/products.php?edit=' . (int)$p['id'])) ?>">ویرایش</a></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </main>
</div>
<script src="<?= htmlspecialchars(assetPath('/assets/js/admin.js')) ?>" defer></script>
</body>
</html>
<?php Performance::finish('admin.products'); ?>
