<?php
session_start();

require_once 'check_permissions.php';

// التحقق من صلاحية الوصول إلى الصفحة الحالية
$screen = basename($_SERVER['PHP_SELF']);
checkPermission($conn, $screen);

// التحقق من تسجيل الدخول
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

require_once 'db_connect.php';

// جلب التصنيفات والوحدات والمخازن من قاعدة البيانات
$categories = $conn->query("SELECT * FROM categories")->fetchAll(PDO::FETCH_ASSOC);
$units = $conn->query("SELECT * FROM units")->fetchAll(PDO::FETCH_ASSOC);
$stores = $conn->query("SELECT * FROM stores")->fetchAll(PDO::FETCH_ASSOC);

// إضافة صنف جديد
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['add_item'])) {
    $barcode = $_POST['barcode'];
    $name = $_POST['name'];
    $category_id = $_POST['category_id'];
    $unit_id = $_POST['unit_id'];
    $min_quantity = $_POST['min_quantity'];
    $initial_stock = $_POST['initial_stock'];
    $store_id = $_POST['store_id'];
    $purchase_price = $_POST['purchase_price'];
    $retail_price = $_POST['retail_price'];
    $wholesale_price = $_POST['wholesale_price'];
    $description = $_POST['description'];

    try {
        $stmt = $conn->prepare("INSERT INTO items (barcode, name, category_id, unit_id, min_quantity, quantity, store_id, purchase_price, retail_price, wholesale_price, description) 
                                VALUES (:barcode, :name, :category_id, :unit_id, :min_quantity, :quantity, :store_id, :purchase_price, :retail_price, :wholesale_price, :description)");
        $stmt->execute([
            ':barcode' => $barcode,
            ':name' => $name,
            ':category_id' => $category_id,
            ':unit_id' => $unit_id,
            ':min_quantity' => $min_quantity,
            ':quantity' => $initial_stock,
            ':store_id' => $store_id,
            ':purchase_price' => $purchase_price,
            ':retail_price' => $retail_price,
            ':wholesale_price' => $wholesale_price,
            ':description' => $description
        ]);
        $_SESSION['success_message'] = "تم إضافة الصنف بنجاح.";
        header("Location: add_item.php");
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "حدث خطأ أثناء إضافة الصنف: " . htmlspecialchars($e->getMessage());
        header("Location: add_item.php");
        exit();
    }
}

// تعديل صنف
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['edit_item'])) {
    $id = $_POST['id'];
    $barcode = $_POST['barcode'];
    $name = $_POST['name'];
    $category_id = $_POST['category_id'];
    $unit_id = $_POST['unit_id'];
    $min_quantity = $_POST['min_quantity'];
    $quantity = $_POST['quantity'];
    $store_id = $_POST['store_id'];
    $purchase_price = $_POST['purchase_price'];
    $retail_price = $_POST['retail_price'];
    $wholesale_price = $_POST['wholesale_price'];
    $description = $_POST['description'];

    try {
        $stmt = $conn->prepare("UPDATE items SET barcode = :barcode, name = :name, category_id = :category_id, unit_id = :unit_id, min_quantity = :min_quantity, quantity = :quantity, store_id = :store_id, purchase_price = :purchase_price, retail_price = :retail_price, wholesale_price = :wholesale_price, description = :description WHERE id = :id");
        $stmt->execute([
            ':id' => $id,
            ':barcode' => $barcode,
            ':name' => $name,
            ':category_id' => $category_id,
            ':unit_id' => $unit_id,
            ':min_quantity' => $min_quantity,
            ':quantity' => $quantity,
            ':store_id' => $store_id,
            ':purchase_price' => $purchase_price,
            ':retail_price' => $retail_price,
            ':wholesale_price' => $wholesale_price,
            ':description' => $description
        ]);
        $_SESSION['success_message'] = "تم تعديل الصنف بنجاح.";
        header("Location: add_item.php");
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "حدث خطأ أثناء تعديل الصنف: " . htmlspecialchars($e->getMessage());
        header("Location: add_item.php");
        exit();
    }
}

// حذف صنف
if (isset($_GET['delete_id'])) {
    $id = $_GET['delete_id'];
    try {
        // التحقق من وجود سجلات مرتبطة في جدول sales_invoice_items
        $stmt = $conn->prepare("SELECT COUNT(*) FROM sales_invoice_items WHERE item_id = :id");
        $stmt->execute([':id' => $id]);
        $count = $stmt->fetchColumn();

        if ($count > 0) {
            // إذا كان هناك سجلات مرتبطة، عرض رسالة خطأ
            $_SESSION['error_message'] = "لا يمكن حذف الصنف لأنه مرتبط بفواتير مبيعات.";
        } else {
            // إذا لم يكن هناك سجلات مرتبطة، نفّذ الحذف
            $stmt = $conn->prepare("DELETE FROM items WHERE id = :id");
            $stmt->execute([':id' => $id]);
            $_SESSION['success_message'] = "تم حذف الصنف بنجاح.";
        }
        header("Location: add_item.php");
        exit();
    } catch (PDOException $e) {
        $_SESSION['error_message'] = "حدث خطأ أثناء محاولة الحذف: " . htmlspecialchars($e->getMessage());
        header("Location: add_item.php");
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Astra - إضافة صنف</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            min-height: 100vh;
            direction: rtl;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #4169E1, #87CEEB);
            overflow-x: hidden;
        }

        .container-fluid {
            padding: 20px;
            height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        .card {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
            padding: 20px;
            margin-bottom: 20px;
            flex-grow: 1;
        }

        .form-label {
            color: #4169E1;
            font-weight: bold;
        }

        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid #4169E1;
            padding: 10px;
            transition: all 0.3s ease;
            width: 100%;
        }

        .form-control:focus, .form-select:focus {
            border-color: #2ECC71;
            box-shadow: 0 0 10px rgba(46, 204, 113, 0.5);
        }

        .btn {
            border-radius: 10px;
            padding: 10px 20px;
            font-weight: bold;
            transition: all 0.3s ease;
        }

        .btn-add {
            background: #2ECC71;
            border: none;
            color: #fff;
        }

        .btn-add:hover {
            background: #27AE60;
            transform: translateY(-2px);
        }

        .btn-cancel {
            background: #E74C3C;
            border: none;
            color: #fff;
        }

        .btn-cancel:hover {
            background: #C0392B;
            transform: translateY(-2px);
        }

        .btn-generate {
            background: #F1C40F;
            border: none;
            color: #fff;
        }

        .btn-generate:hover {
            background: #D4AC0D;
            transform: translateY(-2px);
        }

        .btn-save {
            background: #3498DB;
            border: none;
            color: #fff;
        }

        .btn-save:hover {
            background: #2980B9;
            transform: translateY(-2px);
        }

        .table {
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            width: 100%;
        }

        .table thead {
            background: #4169E1;
            color: #fff;
        }

        .table tbody tr:hover {
            background: rgba(65, 105, 225, 0.1);
        }

        .btn-edit {
            background: #3498DB;
            border: none;
            color: #fff;
        }

        .btn-edit:hover {
            background: #2980B9;
        }

        .btn-delete {
            background: #E74C3C;
            border: none;
            color: #fff;
        }

        .btn-delete:hover {
            background: #C0392B;
        }

        .search-bar {
            margin-bottom: 20px;
        }

        .search-bar .form-control {
            border-color: #9B59B6;
        }

        .search-bar .form-control:focus {
            border-color: #8E44AD;
            box-shadow: 0 0 10px rgba(142, 68, 173, 0.5);
        }

        .row-cols-5 .col-md-2-4 {
            flex: 0 0 20%;
            max-width: 20%;
        }

        #profit-container {
            display: none;
        }

        .modal-content {
            border-radius: 15px;
            background: rgba(255, 255, 255, 0.95);
        }

        .modal-header {
            background: #4169E1;
            color: #fff;
            border-radius: 15px 15px 0 0;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <?php if (isset($_SESSION['error_message'])): ?>
            <div class="alert alert-danger text-center">
                <?php echo htmlspecialchars($_SESSION['error_message']); ?>
                <?php unset($_SESSION['error_message']); ?>
            </div>
        <?php elseif (isset($_SESSION['success_message'])): ?>
            <div class="alert alert-success text-center">
                <?php echo htmlspecialchars($_SESSION['success_message']); ?>
                <?php unset($_SESSION['success_message']); ?>
            </div>
        <?php endif; ?>
        <div class="card">
            <h2 class="text-center mb-4" style="color: #4169E1;"><i class="fas fa-box me-2"></i> إضافة صنف جديد</h2>
            <form method="POST">
                <div class="row row-cols-5 g-3">
                    <div class="col-md-2-4 mb-3">
                        <label class="form-label"><i class="fas fa-barcode me-2"></i> باركود الصنف</label>
                        <div class="input-group">
                            <input type="text" class="form-control" name="barcode" id="barcode" required>
                            <button type="button" class="btn btn-generate" onclick="generateBarcode()"><i class="fas fa-sync-alt me-2"></i> باركود جديد</button>
                        </div>
                    </div>
                    <div class="col-md-2-4 mb-3">
                        <label class="form-label"><i class="fas fa-tag me-2"></i> اسم الصنف</label>
                        <input type="text" class="form-control" name="name" required>
                    </div>
                    <div class="col-md-2-4 mb-3">
                        <label class="form-label"><i class="fas fa-list me-2"></i> التصنيف</label>
                        <select class="form-select" name="category_id" required>
                            <option value="">اختر التصنيف</option>
                            <?php foreach ($categories as $category): ?>
                                <option value="<?php echo $category['id']; ?>"><?php echo $category['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2-4 mb-3">
                        <label class="form-label"><i class="fas fa-ruler me-2"></i> الوحدة</label>
                        <select class="form-select" name="unit_id" required>
                            <option value="">اختر الوحدة</option>
                            <?php foreach ($units as $unit): ?>
                                <option value="<?php echo $unit['id']; ?>"><?php echo $unit['name']; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-2-4 mb-3">
                        <label class="form-label"><i class="fas fa-exclamation-triangle me-2"></i> الحد الأدنى</label>
                        <input type="number" class="form-control" name="min_quantity" required>
                    </div>
                    <div class="col-md-2-4 mb-3">
                        <label class="form-label"><i class="fas fa-cubes me-2"></i> رصيد البداية</label>
                        <input type="number" class="form-control" name="initial_stock" required>
                    </div>
                   <div class="col-md-2-4 mb-3">
    <label class="form-label"><i class="fas fa-store me-2"></i> المخزن</label>
    <select class="form-select" name="store_id" required>
        <option value="">اختر المخزن</option>
        <?php foreach ($stores as $index => $store): ?>
            <option value="<?php echo $store['id']; ?>" <?php echo $index === 0 ? 'selected' : ''; ?>>
                <?php echo $store['name']; ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>
                    <div class="col-md-2-4 mb-3">
                        <label class="form-label"><i class="fas fa-money-bill me-2"></i> سعر الشراء</label>
                        <input type="number" step="0.01" class="form-control" name="purchase_price" id="purchase_price" required oninput="calculateProfit()">
                    </div>
                    <div class="col-md-2-4 mb-3">
                        <label class="form-label"><i class="fas fa-shopping-cart me-2"></i> سعر البيع القطاعي</label>
                        <input type="number" step="0.01" class="form-control" name="retail_price" id="retail_price" required oninput="calculateProfit()">
                    </div>
                    <div class="col-md-2-4 mb-3" id="profit-container">
                        <label class="form-label"><i class="fas fa-percentage me-2"></i> نسبة الربح</label>
                        <input type="text" class="form-control" id="profit_percentage" readonly>
                    </div>
                    <div class="col-md-2-4 mb-3">
                        <label class="form-label"><i class="fas fa-truck-loading me-2"></i> سعر البيع الجملة</label>
                        <input type="number" step="0.01" class="form-control" name="wholesale_price" required>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label"><i class="fas fa-info-circle me-2"></i> وصف الصنف</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                    <div class="col-md-6 mb-3 text-center">
                        <button type="submit" class="btn btn-add me-2" name="add_item"><i class="fas fa-plus me-2"></i> إضافة</button>
                        <button type="button" class="btn btn-cancel" onclick="window.location.href='dashboard.php'"><i class="fas fa-times me-2"></i> إلغاء</button>
                    </div>
                </div>
            </form>
        </div>

        <div class="card">
            <h2 class="text-center mb-4" style="color: #4169E1;"><i class="fas fa-table me-2"></i> قائمة الأصناف</h2>
            <div class="search-bar">
                <input type="text" class="form-control" id="searchInput" placeholder="ابحث بالباركود أو الاسم..." onkeyup="searchItems()">
            </div>
            <div class="table-responsive" style="max-height: 50vh; overflow-y: auto;">
                <table class="table table-striped">
                    <thead>
                        <tr>
                            <th>باركود</th>
                            <th>اسم الصنف</th>
                            <th>التصنيف</th>
                            <th>الوحدة</th>
                            <th>الحد الأدنى</th>
                            <th>الرصيد</th>
                            <th>المخزن</th>
                            <th>سعر الشراء</th>
                            <th>سعر البيع القطاعي</th>
                            <th>سعر البيع الجملة</th>
                            <th>الوصف</th>
                            <th>إجراءات</th>
                        </tr>
                    </thead>
                    <tbody id="itemsTable">
                        <?php
                        $items = $conn->query("SELECT i.*, c.name AS category, u.name AS unit, s.name AS store 
                                               FROM items i 
                                               LEFT JOIN categories c ON i.category_id = c.id 
                                               LEFT JOIN units u ON i.unit_id = u.id 
                                               LEFT JOIN stores s ON i.store_id = s.id")->fetchAll(PDO::FETCH_ASSOC);
                        foreach ($items as $item):
                        ?>
                            <tr>
                                <td><?php echo $item['barcode']; ?></td>
                                <td><?php echo $item['name']; ?></td>
                                <td><?php echo $item['category']; ?></td>
                                <td><?php echo $item['unit']; ?></td>
                                <td><?php echo $item['min_quantity']; ?></td>
                                <td><?php echo $item['quantity']; ?></td>
                                <td><?php echo $item['store']; ?></td>
                                <td><?php echo $item['purchase_price']; ?></td>
                                <td><?php echo $item['retail_price']; ?></td>
                                <td><?php echo $item['wholesale_price']; ?></td>
                                <td><?php echo $item['description']; ?></td>
                                <td>
                                    <button class="btn btn-edit btn-sm me-1" onclick="editItem(<?php echo $item['id']; ?>, '<?php echo $item['barcode']; ?>', '<?php echo $item['name']; ?>', '<?php echo $item['category_id']; ?>', '<?php echo $item['unit_id']; ?>', '<?php echo $item['min_quantity']; ?>', '<?php echo $item['quantity']; ?>', '<?php echo $item['store_id']; ?>', '<?php echo $item['purchase_price']; ?>', '<?php echo $item['retail_price']; ?>', '<?php echo $item['wholesale_price']; ?>', '<?php echo $item['description']; ?>')"><i class="fas fa-edit"></i></button>
                                    <button class="btn btn-delete btn-sm" onclick="deleteItem(<?php echo $item['id']; ?>)"><i class="fas fa-trash"></i></button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Modal لتعديل الصنف -->
    <div class="modal fade" id="editItemModal" tabindex="-1" aria-labelledby="editItemModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editItemModalLabel"><i class="fas fa-edit me-2"></i> تعديل الصنف</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form method="POST" id="editItemForm">
                        <input type="hidden" name="id" id="edit_id">
                        <div class="row row-cols-5 g-3">
                            <div class="col-md-2-4 mb-3">
                                <label class="form-label"><i class="fas fa-barcode me-2"></i> باركود الصنف</label>
                                <input type="text" class="form-control" name="barcode" id="edit_barcode" required>
                            </div>
                            <div class="col-md-2-4 mb-3">
                                <label class="form-label"><i class="fas fa-tag me-2"></i> اسم الصنف</label>
                                <input type="text" class="form-control" name="name" id="edit_name" required>
                            </div>
                            <div class="col-md-2-4 mb-3">
                                <label class="form-label"><i class="fas fa-list me-2"></i> التصنيف</label>
                                <select class="form-select" name="category_id" id="edit_category_id" required>
                                    <option value="">اختر التصنيف</option>
                                    <?php foreach ($categories as $category): ?>
                                        <option value="<?php echo $category['id']; ?>"><?php echo $category['name']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2-4 mb-3">
                                <label class="form-label"><i class="fas fa-ruler me-2"></i> الوحدة</label>
                                <select class="form-select" name="unit_id" id="edit_unit_id" required>
                                    <option value="">اختر الوحدة</option>
                                    <?php foreach ($units as $unit): ?>
                                        <option value="<?php echo $unit['id']; ?>"><?php echo $unit['name']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2-4 mb-3">
                                <label class="form-label"><i class="fas fa-exclamation-triangle me-2"></i> الحد الأدنى</label>
                                <input type="number" class="form-control" name="min_quantity" id="edit_min_quantity" required>
                            </div>
                            <div class="col-md-2-4 mb-3">
                                <label class="form-label"><i class="fas fa-cubes me-2"></i> الرصيد</label>
                                <input type="number" class="form-control" name="quantity" id="edit_quantity" required>
                            </div>
                            <div class="col-md-2-4 mb-3">
                                <label class="form-label"><i class="fas fa-store me-2"></i> المخزن</label>
                                <select class="form-select" name="store_id" id="edit_store_id" required>
                                    <option value="">اختر المخزن</option>
                                    <?php foreach ($stores as $store): ?>
                                        <option value="<?php echo $store['id']; ?>"><?php echo $store['name']; ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2-4 mb-3">
                                <label class="form-label"><i class="fas fa-money-bill me-2"></i> سعر الشراء</label>
                                <input type="number" step="0.01" class="form-control" name="purchase_price" id="edit_purchase_price" required>
                            </div>
                            <div class="col-md-2-4 mb-3">
                                <label class="form-label"><i class="fas fa-shopping-cart me-2"></i> سعر البيع القطاعي</label>
                                <input type="number" step="0.01" class="form-control" name="retail_price" id="edit_retail_price" required>
                            </div>
                            <div class="col-md-2-4 mb-3">
                                <label class="form-label"><i class="fas fa-truck-loading me-2"></i> سعر البيع الجملة</label>
                                <input type="number" step="0.01" class="form-control" name="wholesale_price" id="edit_wholesale_price" required>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label class="form-label"><i class="fas fa-info-circle me-2"></i> وصف الصنف</label>
                                <textarea class="form-control" name="description" id="edit_description" rows="3"></textarea>
                            </div>
                            <div class="col-md-6 mb-3 text-center">
                                <button type="submit" class="btn btn-save me-2" name="edit_item"><i class="fas fa-save me-2"></i> حفظ</button>
                                <button type="button" class="btn btn-cancel" data-bs-dismiss="modal"><i class="fas fa-times me-2"></i> إلغاء</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // توليد باركود عشوائي
        function generateBarcode() {
            const random = Math.floor(1000000000 + Math.random() * 9000000000);
            document.getElementById('barcode').value = random;
        }

        // حساب نسبة الربح
        function calculateProfit() {
            const purchasePrice = parseFloat(document.getElementById('purchase_price').value) || 0;
            const retailPrice = parseFloat(document.getElementById('retail_price').value) || 0;
            const profitContainer = document.getElementById('profit-container');
            const profitPercentage = document.getElementById('profit_percentage');

            if (purchasePrice > 0 && retailPrice > 0) {
                const profit = ((retailPrice - purchasePrice) / purchasePrice) * 100;
                profitPercentage.value = profit.toFixed(2) + '%';
                profitContainer.style.display = 'block';
            } else {
                profitContainer.style.display = 'none';
            }
        }

        // البحث في الجدول
        function searchItems() {
            const input = document.getElementById('searchInput').value.toLowerCase();
            const table = document.getElementById('itemsTable');
            const rows = table.getElementsByTagName('tr');

            for (let i = 0; i < rows.length; i++) {
                const barcode = rows[i].getElementsByTagName('td')[0];
                const name = rows[i].getElementsByTagName('td')[1];
                if (barcode && name) {
                    const barcodeText = barcode.textContent || barcode.innerText;
                    const nameText = name.textContent || name.innerText;
                    if (barcodeText.toLowerCase().indexOf(input) > -1 || nameText.toLowerCase().indexOf(input) > -1) {
                        rows[i].style.display = '';
                    } else {
                        rows[i].style.display = 'none';
                    }
                }
            }
        }

        // تعديل صنف
        function editItem(id, barcode, name, category_id, unit_id, min_quantity, quantity, store_id, purchase_price, retail_price, wholesale_price, description) {
            document.getElementById('edit_id').value = id;
            document.getElementById('edit_barcode').value = barcode;
            document.getElementById('edit_name').value = name;
            document.getElementById('edit_category_id').value = category_id;
            document.getElementById('edit_unit_id').value = unit_id;
            document.getElementById('edit_min_quantity').value = min_quantity;
            document.getElementById('edit_quantity').value = quantity;
            document.getElementById('edit_store_id').value = store_id;
            document.getElementById('edit_purchase_price').value = purchase_price;
            document.getElementById('edit_retail_price').value = retail_price;
            document.getElementById('edit_wholesale_price').value = wholesale_price;
            document.getElementById('edit_description').value = description;

            const modal = new bootstrap.Modal(document.getElementById('editItemModal'));
            modal.show();
        }

        // حذف صنف
        function deleteItem(id) {
            if (confirm('هل أنت متأكد من حذف هذا الصنف؟')) {
                window.location.href = 'add_item.php?delete_id=' + id;
            }
        }
    </script>
</body>
</html>