<?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';

$errors = [];
$success = false;

// --- معالجة الإضافة (POST) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_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.';
    }

    // التحقق من تكرار الـ SKU إذا وجد
    if ($sku !== '') {
        $check = $pdo->prepare("SELECT id FROM products WHERE sku = ? LIMIT 1");
        $check->execute([$sku]);
        if ($check->fetch()) {
            $errors[] = $is_ar ? 'هذا الـ SKU مستخدم بالفعل لمنتج آخر.' : 'This SKU is already assigned to another product.';
        }
    }

    if (empty($errors)) {
        try {
            $sql = "INSERT INTO products (sku, name_en, cost, price, stock, created_at) VALUES (?, ?, ?, ?, ?, NOW())";
            $stmt = $pdo->prepare($sql);
            $stmt->execute([$sku, $name, $cost, $price, $stock]);
            $success = true;
            
            // إعادة توجيه بسيطة أو مسح النموذج بعد النجاح
            // header('Refresh: 2; URL=inventory.php'); 
        } catch (Exception $e) {
            $errors[] = $e->getMessage();
        }
    }
}
?>
<!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 ? 'إضافة صنف جديد' : 'Add New Product' ?> | Top Accessories</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: 45px;
            position: relative; overflow: hidden;
        }

        .lux-card::before {
            content: ""; position: absolute; top: 0; left: 0; right: 0; height: 6px;
            background: linear-gradient(90deg, #10b981, #3b82f6);
        }

        .header-section { margin-bottom: 40px; }
        .header-section h2 { font-weight: 800; font-size: 1.85rem; letter-spacing: -0.02em; margin-bottom: 8px; }

        .form-label { font-weight: 700; color: #64748b; font-size: 0.85rem; text-transform: uppercase; letter-spacing: 0.05em; margin-bottom: 10px; }
        
        .lux-input {
            height: 56px; border-radius: 16px; border: 2px solid var(--border-color);
            padding: 0 20px; 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-add {
            background: var(--brand-primary); color: white; border-radius: 50px;
            padding: 16px 45px; font-weight: 700; border: none; transition: 0.3s;
            box-shadow: 0 10px 20px -5px rgba(79, 70, 229, 0.4); font-size: 1.1rem;
        }
        .btn-add: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: 22px; border: none; font-weight: 600; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.05); }
        
        .input-icon-wrapper { position: relative; }
        .input-icon { position: absolute; top: 18px; <?= $is_ar?'left':'right' ?>: 20px; color: #94a3b8; }
    </style>
</head>
<body>

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

    <div class="container">
        <!-- Dashboard Top Navigation -->
        <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="d-flex gap-2">
                <a href="?lang=<?= $is_ar ? 'en' : 'ar' ?>" class="btn-back px-3">🌐</a>
            </div>
        </div>

        <div class="lux-card">
            <div class="header-section">
                <h2><?= $is_ar ? 'إضافة منتج للمخزون' : 'Add New Item to Stock' ?></h2>
                <p class="text-muted"><?= $is_ar ? 'أدخل تفاصيل المنتج الجديد بدقة لتحديث قاعدة بيانات المخزون.' : 'Enter new product details carefully to update the inventory database.' ?></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-2x"></i>
                    <div>
                        <div class="fw-bold fs-5"><?= $is_ar ? 'تمت العملية بنجاح!' : 'Success!' ?></div>
                        <div class="small opacity-75"><?= $is_ar ? 'تم تسجيل المنتج الجديد في النظام.' : 'New product has been registered in the system.' ?></div>
                    </div>
                </div>
            <?php endif; ?>

            <?php if (!empty($errors)): ?>
                <div class="alert alert-danger alert-lux mb-4">
                    <div class="fw-bold mb-2"><?= $is_ar ? 'يوجد أخطاء:' : 'Errors found:' ?></div>
                    <ul class="m-0 small">
                        <?php foreach($errors as $err) echo "<li>".esc($err)."</li>"; ?>
                    </ul>
                </div>
            <?php endif; ?>

            <form method="post" id="addProductForm">
                <input type="hidden" name="add_product" value="1">
                
                <div class="row g-4">
                    <!-- SKU & Name -->
                    <div class="col-md-6">
                        <label class="form-label">SKU / Barcode</label>
                        <div class="input-icon-wrapper">
                            <i class="fa fa-barcode input-icon"></i>
                            <input name="sku" class="form-control lux-input" style="padding-<?= $is_ar?'right':'left' ?>: 45px;" placeholder="<?= $is_ar ? 'أدخل كود الصنف' : 'Enter product SKU' ?>" autofocus>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <label class="form-label"><?= $is_ar ? 'اسم المنتج' : 'Product Name' ?></label>
                        <div class="input-icon-wrapper">
                            <i class="fa fa-tag input-icon"></i>
                            <input name="name_en" class="form-control lux-input" style="padding-<?= $is_ar?'right':'left' ?>: 45px;" placeholder="<?= $is_ar ? 'اسم المنتج بالكامل' : 'Full product name' ?>" required>
                        </div>
                    </div>

                    <!-- Pricing Section -->
                    <div class="col-md-4">
                        <label class="form-label"><?= $is_ar ? 'سعر التكلفة' : 'Cost Price' ?></label>
                        <input type="number" step="0.01" name="cost" class="form-control lux-input text-center" placeholder="0.00">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label"><?= $is_ar ? 'سعر البيع' : 'Sale Price' ?></label>
                        <input type="number" step="0.01" name="price" class="form-control lux-input text-center fw-bold" style="color: var(--brand-primary);" placeholder="0.00">
                    </div>
                    <div class="col-md-4">
                        <label class="form-label"><?= $is_ar ? 'الكمية الافتتاحية' : 'Initial Stock' ?></label>
                        <input type="number" name="stock" class="form-control lux-input text-center" value="0">
                    </div>

                    <div class="col-12 mt-5 text-center">
                        <button type="submit" class="btn-add">
                            <i class="fa fa-plus-circle me-2"></i> 
                            <?= $is_ar ? 'إضافة المنتج الآن' : 'Create Product Now' ?>
                        </button>
                    </div>
                </div>
            </form>
        </div>

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

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // تنظيف النموذج بعد النجاح (اختياري)
        <?php if ($success): ?>
            document.getElementById('addProductForm').reset();
        <?php endif; ?>
    </script>
</body>
</html>