<?php
session_start();
require_once '../includes/auth.php';
require_once __DIR__ . '/stock_helpers.php';

if (!function_exists('e')) {
    function e($value){ return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8'); }
}

$id = isset($_GET['product_id']) ? (int)$_GET['product_id'] : (int)($_POST['product_id'] ?? 0);
if ($id <= 0) {
    header('Location: stock_manage.php');
    exit;
}

$product = nay_stock_fetch_target($conn, 'product', $id);
if (!$product) {
    $_SESSION['stock_error'] = 'المنتج غير موجود.';
    header('Location: list.php');
    exit;
}
if ((int)($product['has_variants'] ?? 0) === 1) {
    header('Location: variants.php?product_id=' . $id);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $mode = (string)($_POST['mode'] ?? 'set');
        $qty = (int)($_POST['stock_qty'] ?? 0);
        $lowStockAlert = max(0, (int)($_POST['low_stock_alert'] ?? 0));
        $status = isset($_POST['status']) ? (int)$_POST['status'] : 1;
        $reasonCode = trim((string)($_POST['reason_code'] ?? 'manual_adjustment')) ?: 'manual_adjustment';
        $notes = trim((string)($_POST['notes'] ?? ''));

        $conn->begin_transaction();
        nay_stock_apply_change($conn, 'product', $id, $mode, $qty, [
            'admin_id' => current_admin_id(),
            'source' => 'admin_manual',
            'reason_code' => $reasonCode,
            'notes' => $notes,
        ]);
        nay_stock_update_meta($conn, 'product', $id, [
            'low_stock_alert' => $lowStockAlert,
            'status' => $status,
        ]);
        $conn->commit();
        $_SESSION['stock_success'] = 'تم تحديث مخزون المنتج وحفظ السجل.';
    } catch (Throwable $e) {
        $conn->rollback();
        $_SESSION['stock_error'] = 'خطأ: ' . $e->getMessage();
    }
    header('Location: inventory.php?product_id=' . $id);
    exit;
}

$product = nay_stock_fetch_target($conn, 'product', $id);
$stockSuccess = $_SESSION['stock_success'] ?? '';
$stockError = $_SESSION['stock_error'] ?? '';
unset($_SESSION['stock_success'], $_SESSION['stock_error']);
$recentMoves = nay_stock_fetch_movements($conn, ['product_id' => $id, 'limit' => 12]);
$reasonLabels = nay_stock_reason_labels();
$badge = nay_stock_badge_meta((string)($product['state'] ?? 'healthy'));

require_once '../includes/header.php';
require_once '../includes/sidebar.php';
?>
<style>
.stock-single-page{padding:24px;direction:rtl}.stock-single-wrap{max-width:1350px;margin:0 auto}.stock-single-hero{background:linear-gradient(135deg,#163750,#214f75);color:#fff;border-radius:26px;padding:24px;display:flex;justify-content:space-between;gap:18px;align-items:center;flex-wrap:wrap;margin-bottom:18px}.stock-single-hero h1{margin:0 0 8px;font-size:30px;font-weight:900}.stock-single-hero p{margin:0;color:rgba(255,255,255,.82)}.hero-actions{display:flex;gap:10px;flex-wrap:wrap}.hero-btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;padding:12px 18px;border-radius:14px;text-decoration:none;font-weight:800}.hero-btn.light{background:#fff;color:#163750}.hero-btn.dark{background:rgba(255,255,255,.12);color:#fff;border:1px solid rgba(255,255,255,.2)}.stock-grid{display:grid;grid-template-columns:1.1fr .9fr;gap:18px}.stock-card{background:#fff;border:1px solid #e7eef5;border-radius:24px;box-shadow:0 16px 40px rgba(16,24,40,.05)}.stock-card-header{padding:18px 22px;border-bottom:1px solid #edf2f7;display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap}.stock-card-header h3{margin:0;font-size:18px;color:#17324d}.stock-card-body{padding:22px}.stock-alert{border-radius:18px;padding:14px 16px;margin-bottom:18px;font-weight:700}.stock-alert.success{background:#ecfdf3;border:1px solid #b7ebc6;color:#166534}.stock-alert.error{background:#fff1f1;border:1px solid #ffd5d5;color:#b42318}.product-head{display:grid;grid-template-columns:120px 1fr;gap:18px;align-items:center}.product-thumb{width:120px;height:120px;border-radius:22px;overflow:hidden;background:#f4f7fb;border:1px solid #dae7f1;display:flex;align-items:center;justify-content:center}.product-thumb img{width:100%;height:100%;object-fit:cover}.product-fallback{color:#8aa0b7;font-size:38px}.meta-lines{display:flex;flex-wrap:wrap;gap:10px;margin-top:12px}.chip{display:inline-flex;align-items:center;gap:8px;padding:8px 12px;border-radius:999px;font-size:12px;font-weight:800}.chip.blue{background:#eaf4ff;color:#0f5ca8}.chip.red{background:#fff1f1;color:#b42318}.chip.orange{background:#fff7ed;color:#c2410c}.chip.green{background:#ecfdf3;color:#166534}.detail-list{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-top:18px}.detail-box{background:#f8fbff;border:1px solid #e5eef6;border-radius:18px;padding:14px}.detail-box .label{font-size:12px;color:#71839a;margin-bottom:8px;font-weight:700}.detail-box .value{font-size:18px;color:#17324d;font-weight:900}.form-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}.field label{display:block;margin-bottom:7px;font-weight:800;color:#23465f}.field input,.field select,.field textarea{width:100%;padding:12px 14px;border:1px solid #d5e2ec;border-radius:14px;background:#fff}.field textarea{min-height:120px;resize:vertical}.btn-row{display:flex;gap:10px;flex-wrap:wrap;margin-top:18px}.btn-row button{border:none;border-radius:14px;padding:12px 18px;font-weight:900;cursor:pointer}.btn-set{background:#153b58;color:#fff}.btn-add{background:linear-gradient(135deg,#2f80ed,#56ccf2);color:#fff}.btn-zero{background:#b42318;color:#fff}.movement-table{width:100%;border-collapse:collapse}.movement-table th,.movement-table td{padding:12px;border-bottom:1px solid #edf2f7;text-align:right;vertical-align:top}.movement-table th{background:#f8fbff;color:#23465f;font-size:13px}.muted{color:#71839a;font-size:12px}.empty-state{padding:22px;text-align:center;color:#71839a}@media (max-width:980px){.stock-grid,.detail-list,.form-grid,.product-head{grid-template-columns:1fr}}
</style>
<div class="stock-single-page"><div class="stock-single-wrap">
    <div class="stock-single-hero">
        <div>
            <h1>إدارة مخزون المنتج</h1>
            <p>تعديل مباشر للمنتج البسيط مع سجل حركة واضح وربط موحّد بالمخزون.</p>
        </div>
        <div class="hero-actions">
            <a class="hero-btn light" href="stock_manage.php">إدارة المخزون</a>
            <a class="hero-btn dark" href="stock_movements.php?product_id=<?= (int)$id ?>">سجل الحركة</a>
        </div>
    </div>

    <?php if ($stockSuccess): ?><div class="stock-alert success"><?= e($stockSuccess) ?></div><?php endif; ?>
    <?php if ($stockError): ?><div class="stock-alert error"><?= e($stockError) ?></div><?php endif; ?>

    <div class="stock-grid">
        <div class="stock-card">
            <div class="stock-card-header"><h3>بيانات المنتج الحالية</h3><span class="chip <?= e($badge['class']) ?>"><?= e($badge['label']) ?></span></div>
            <div class="stock-card-body">
                <div class="product-head">
                    <div class="product-thumb">
                        <?php $img = nay_stock_resolve_image((string)($product['image'] ?? '')); ?>
                        <?php if ($img): ?><img src="<?= e($img) ?>" alt=""><?php else: ?><div class="product-fallback">🧴</div><?php endif; ?>
                    </div>
                    <div>
                        <h2 style="margin:0 0 8px;color:#17324d"><?= e($product['display_name'] ?? '') ?></h2>
                        <div class="muted">SKU: <?= e($product['sku'] ?: '—') ?></div>
                        <div class="meta-lines">
                            <span class="chip blue">المتوفر: <?= number_format((int)($product['stock_qty'] ?? 0)) ?></span>
                            <span class="chip orange">حد التنبيه: <?= number_format((int)($product['effective_threshold'] ?? 0)) ?></span>
                            <span class="chip green">المصدر: منتج بسيط</span>
                        </div>
                    </div>
                </div>
                <div class="detail-list">
                    <div class="detail-box"><div class="label">الكمية الحالية</div><div class="value"><?= number_format((int)($product['stock_qty'] ?? 0)) ?></div></div>
                    <div class="detail-box"><div class="label">الحالة</div><div class="value"><?= (int)($product['status'] ?? 0) === 1 ? 'مفعّل' : 'معطّل' ?></div></div>
                    <div class="detail-box"><div class="label">نوع التتبع</div><div class="value">مخزون مباشر</div></div>
                </div>
            </div>
        </div>

        <div class="stock-card">
            <div class="stock-card-header"><h3>تنفيذ تعديل جديد</h3><span class="muted">كل تعديل يُحفظ داخل سجل الحركة</span></div>
            <div class="stock-card-body">
                <form method="post">
                    <input type="hidden" name="product_id" value="<?= (int)$id ?>">
                    <div class="form-grid">
                        <div class="field">
                            <label>القيمة</label>
                            <input type="number" name="stock_qty" min="0" value="<?= (int)($product['stock_qty'] ?? 0) ?>">
                        </div>
                        <div class="field">
                            <label>حد التنبيه</label>
                            <input type="number" name="low_stock_alert" min="0" value="<?= (int)($product['low_stock_alert'] ?? 0) ?>">
                        </div>
                        <div class="field">
                            <label>حالة المنتج</label>
                            <select name="status">
                                <option value="1" <?= (int)($product['status'] ?? 0) === 1 ? 'selected' : '' ?>>مفعّل</option>
                                <option value="0" <?= (int)($product['status'] ?? 0) === 0 ? 'selected' : '' ?>>معطّل</option>
                            </select>
                        </div>
                        <div class="field">
                            <label>سبب التعديل</label>
                            <select name="reason_code">
                                <?php foreach ($reasonLabels as $key => $label): ?>
                                    <option value="<?= e($key) ?>"><?= e($label) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    <div class="field" style="margin-top:14px">
                        <label>ملاحظات</label>
                        <textarea name="notes" placeholder="اكتب ملاحظة مختصرة عن سبب الحركة أو المصدر..."></textarea>
                    </div>
                    <div class="btn-row">
                        <button class="btn-set" type="submit" name="mode" value="set">تعيين المخزون</button>
                        <button class="btn-add" type="submit" name="mode" value="add">إضافة على المخزون</button>
                        <button class="btn-zero" type="submit" name="mode" value="zero" onclick="return confirm('هل تريد تصفير مخزون هذا المنتج؟');">تصفير المخزون</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div class="stock-card" style="margin-top:18px">
        <div class="stock-card-header"><h3>آخر حركات المخزون</h3><a class="hero-btn light" style="padding:10px 14px" href="stock_movements.php?product_id=<?= (int)$id ?>">فتح السجل الكامل</a></div>
        <div class="stock-card-body">
            <?php if ($recentMoves): ?>
                <table class="movement-table">
                    <thead><tr><th>الوقت</th><th>الإجراء</th><th>قبل / بعد</th><th>المصدر</th><th>الملاحظات</th></tr></thead>
                    <tbody>
                    <?php foreach ($recentMoves as $move): ?>
                        <tr>
                            <td><?= e($move['created_at'] ?? '') ?></td>
                            <td>
                                <strong><?= e($reasonLabels[$move['reason_code'] ?? ''] ?? ($move['action_type'] ?? '—')) ?></strong>
                                <div class="muted">نوع الحركة: <?= e($move['action_type'] ?? '—') ?></div>
                            </td>
                            <td>
                                <div>قبل: <strong><?= number_format((int)($move['qty_before'] ?? 0)) ?></strong></div>
                                <div>التغير: <strong><?= number_format((int)($move['qty_change'] ?? 0)) ?></strong></div>
                                <div>بعد: <strong><?= number_format((int)($move['qty_after'] ?? 0)) ?></strong></div>
                            </td>
                            <td>
                                <div><?= e($move['admin_name'] ?? 'النظام') ?></div>
                                <div class="muted"><?= e($move['source'] ?? '—') ?></div>
                            </td>
                            <td><?= e($move['notes'] ?? '—') ?></td>
                        </tr>
                    <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="empty-state">لا توجد حركات مخزون مسجلة لهذا المنتج حتى الآن.</div>
            <?php endif; ?>
        </div>
    </div>
</div></div>
<?php require_once '../includes/footer.php'; ?>
