<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/src/auth.php';
require_login();

// --- الإعدادات الأولية ---
date_default_timezone_set('Asia/Beirut');
if (session_status() === PHP_SESSION_NONE) session_start();

function esc($v){ return htmlspecialchars($v ?? '', ENT_QUOTES, 'UTF-8'); }

$lang = $_GET['lang'] ?? ($_SESSION['lang'] ?? 'ar');
if (isset($_GET['lang'])) { $_SESSION['lang'] = $_GET['lang'] === 'ar' ? 'ar' : 'en'; $lang = $_SESSION['lang']; }
$is_ar = $lang === 'ar';

// جلب معرف المنتج
$id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($id <= 0) {
    header('Location: inventory.php');
    exit;
}

$errors = [];
$success = false;

// --- معالجة التحديث (POST) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_product'])) {
    $sku   = trim($_POST['sku'] ?? '');
    $name  = trim($_POST['name_en'] ?? '');
    $cost  = floatval($_POST['cost'] ?? 0);
    $price = floatval($_POST['price'] ?? 0);
    $stock = intval($_POST['stock'] ?? 0);

    if ($name === '') {
        $errors[] = $is_ar ? 'اسم المنتج مطلوب.' : 'Product name is required.';
    }

    if (empty($errors)) {
        try {
            // تم إزالة حقل name_ar من الاستعلام بناءً على طلبك
            $sql = "UPDATE products SET sku = ?, name_en = ?, cost = ?, price = ?, stock = ? WHERE id = ?";
            $params = [$sku, $name, $cost, $price, $stock, $id];
            
            $stmt = $pdo->prepare($sql);
            $stmt->execute($params);
            $success = true;
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}

// --- جلب بيانات المنتج الحالية ---
$stmt = $pdo->prepare("SELECT * FROM products WHERE id = ? LIMIT 1");
$stmt->execute([$id]);
$product = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$product) {
    die($is_ar ? "المنتج غير موجود." : "Product not found.");
}
?>
<!doctype html>
<html lang="<?= $lang ?>" dir="<?= $is_ar ? 'rtl' : 'ltr' ?>">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title><?= $is_ar ? 'تعديل صنف' : 'Edit Product' ?> | <?= esc($product['name_en']) ?></title>
    
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700;800&family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
    
    <style>
        :root {
            --brand-primary: #4f46e5;
            --brand-indigo: #6366f1;
            --surface: #ffffff;
            --bg-main: #f8fafc;
            --border-color: #e2e8f0;
            --text-main: #0f172a;
        }

        body {
            font-family: <?= $is_ar ? "'Cairo', sans-serif" : "'Plus Jakarta Sans', sans-serif" ?>;
            background-color: var(--bg-main);
            color: var(--text-main);
            padding: 40px 0;
        }

        .bg-pattern {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1;
            background-image: radial-gradient(#cbd5e1 0.8px, transparent 0.8px);
            background-size: 24px 24px; opacity: 0.4;
        }

        .container { max-width: 800px; }

        .lux-card {
            background: var(--surface); border-radius: 32px; border: 1px solid var(--border-color);
            box-shadow: 0 20px 50px -12px rgba(0, 0, 0, 0.05); padding: 40px;
            position: relative; overflow: hidden;
        }

        .lux-card::before {
            content: ""; position: absolute; top: 0; left: 0; right: 0; height: 6px;
            background: linear-gradient(90deg, var(--brand-primary), var(--brand-indigo));
        }

        .header-section { margin-bottom: 35px; }
        .header-section h2 { font-weight: 800; font-size: 1.75rem; letter-spacing: -0.02em; margin-bottom: 5px; }

        .form-label { font-weight: 700; color: #64748b; font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 10px; }
        
        .lux-input {
            height: 54px; border-radius: 14px; border: 2px solid var(--border-color);
            padding: 0 18px; font-size: 1rem; font-weight: 600; transition: 0.3s; background: #fcfcfd;
        }
        .lux-input:focus { border-color: var(--brand-primary); background: #fff; box-shadow: 0 0 0 5px rgba(79, 70, 229, 0.1); outline: none; }

        .btn-update {
            background: var(--brand-primary); color: white; border-radius: 50px;
            padding: 15px 40px; font-weight: 700; border: none; transition: 0.3s;
            box-shadow: 0 10px 20px -5px rgba(79, 70, 229, 0.4);
        }
        .btn-update:hover { background: #4338ca; transform: translateY(-2px); box-shadow: 0 15px 30px -5px rgba(79, 70, 229, 0.5); }

        .btn-back {
            background: #fff; color: #64748b; border: 1px solid var(--border-color);
            border-radius: 50px; padding: 12px 25px; font-weight: 700; transition: 0.2s;
            text-decoration: none; display: inline-flex; align-items: center; gap: 8px;
        }
        .btn-back:hover { background: #f8fafc; color: var(--text-main); }

        .alert-lux { border-radius: 20px; padding: 20px; border: none; font-weight: 600; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); }
    </style>
</head>
<body>

    <div class="bg-pattern"></div>

    <div class="container">
        <!-- Breadcrumb / Back -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <a href="inventory.php" class="btn-back">
                <i class="fa fa-arrow-<?= $is_ar?'right':'left' ?>"></i> 
                <?= $is_ar ? 'العودة للمخزن' : 'Back to Inventory' ?>
            </a>
            <div class="text-muted small fw-bold"><?= $is_ar ? 'معرف المنتج:' : 'Product ID:' ?> #<?= $id ?></div>
        </div>

        <div class="lux-card">
            <div class="header-section">
                <h2><?= $is_ar ? 'تعديل بيانات المنتج' : 'Edit Product Details' ?></h2>
                <p class="text-muted"><?= $is_ar ? 'قم بتحديث معلومات الصنف، الأسعار أو الكميات المتاحة.' : 'Update item specifications, pricing or available stock.' ?></p>
            </div>

            <?php if ($success): ?>
                <div class="alert alert-success alert-lux mb-4 d-flex align-items-center gap-3">
                    <i class="fa fa-check-circle fa-lg"></i>
                    <span><?= $is_ar ? '✅ تم تحديث بيانات المنتج بنجاح.' : '✅ Product updated successfully.' ?></span>
                </div>
            <?php endif; ?>

            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger alert-lux mb-4">
                    <ul class="m-0">
                        <?php foreach($errors as $err) echo "<li>".esc($err)."</li>"; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <form method="post">
                <input type="hidden" name="update_product" value="1">
                
                <div class="row g-4">
                    <!-- SKU & Name -->
                    <div class="col-md-6">
                        <label class="form-label">SKU / Barcode</label>
                        <input name="sku" class="form-control lux-input" value="<?= esc($product['sku']) ?>" placeholder="e.g. PRD-1002">
                    </div>
                    <div class="col-md-6">
                        <label class="form-label"><?= $is_ar ? 'اسم المنتج' : 'Product Name' ?></label>
                        <input name="name_en" class="form-control lux-input" value="<?= esc($product['name_en']) ?>" required>
                    </div>

                    <!-- Pricing Section -->
                    <div class="col-md-4">
                        <label class="form-label"><?= $is_ar ? 'سعر التكلفة' : 'Cost Price' ?></label>
                        <div class="input-group">
                            <input type="number" step="0.01" name="cost" class="form-control lux-input" value="<?= $product['cost'] ?>">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label"><?= $is_ar ? 'سعر البيع' : 'Sale Price' ?></label>
                        <div class="input-group">
                            <input type="number" step="0.01" name="price" class="form-control lux-input" value="<?= $product['price'] ?>" style="color: var(--brand-primary);">
                        </div>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label"><?= $is_ar ? 'المخزون الحالي' : 'Current Stock' ?></label>
                        <input type="number" name="stock" class="form-control lux-input" value="<?= $product['stock'] ?>" style="color: <?= $product['stock'] <= 5 ? 'red' : '#10b981' ?>;">
                    </div>

                    <div class="col-12 mt-5 text-center">
                        <button type="submit" class="btn-update">
                            <i class="fa fa-save me-2"></i> 
                            <?= $is_ar ? 'حفظ التعديلات' : 'Save Changes' ?>
                        </button>
                    </div>
                </div>
            </form>
        </div>

        <div class="text-center mt-5 text-muted small fw-bold">
            Top Accessories &bull; Smart Inventory System &copy; 2025
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>