<?php
require_once __DIR__ . '/includes/header.php';

if (!canView('stock_settings')) {
    echo '<div class="alert alert-danger">عذراً، ليس لديك صلاحية الوصول لهذه الصفحة.</div>';
    require_once __DIR__ . '/includes/footer.php';
    exit;
}

$success = '';
$error = '';

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $type = $_POST['type'] ?? ''; // 'store' or 'category'
    $id = $_POST['id'] ?? 0;
    $name = $_POST['name'] ?? '';
    $desc = $_POST['description'] ?? ''; // location or description

    if ($action === 'add' && canAdd('stock_settings')) {
        if ($name) {
            if ($type === 'store') {
                $stmt = db()->prepare("INSERT INTO stock_stores (name, location) VALUES (?, ?)");
                $stmt->execute([$name, $desc]);
            } else {
                $stmt = db()->prepare("INSERT INTO stock_categories (name, description) VALUES (?, ?)");
                $stmt->execute([$name, $desc]);
            }
            $success = 'تم الإضافة بنجاح';
        }
    } elseif ($action === 'edit' && canEdit('stock_settings')) {
        if ($name && $id) {
            if ($type === 'store') {
                $stmt = db()->prepare("UPDATE stock_stores SET name=?, location=? WHERE id=?");
                $stmt->execute([$name, $desc, $id]);
            } else {
                $stmt = db()->prepare("UPDATE stock_categories SET name=?, description=? WHERE id=?");
                $stmt->execute([$name, $desc, $id]);
            }
            $success = 'تم التحديث بنجاح';
        }
    } elseif ($action === 'delete' && canDelete('stock_settings')) {
        if ($id) {
            try {
                if ($type === 'store') {
                    $stmt = db()->prepare("DELETE FROM stock_stores WHERE id=?");
                    $stmt->execute([$id]);
                } else {
                    $stmt = db()->prepare("DELETE FROM stock_categories WHERE id=?");
                    $stmt->execute([$id]);
                }
                $success = 'تم الحذف بنجاح';
            } catch (PDOException $e) {
                $error = 'لا يمكن الحذف لوجود بيانات مرتبطة';
            }
        }
    }
}

$stores = db()->query("SELECT * FROM stock_stores ORDER BY name ASC")->fetchAll();
$categories = db()->query("SELECT * FROM stock_categories ORDER BY name ASC")->fetchAll();

?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">إعدادات المخزون</h1>
</div>

<?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?= $success ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <?= $error ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<ul class="nav nav-tabs mb-4" id="stockSettingsTabs" role="tablist">
    <li class="nav-item" role="presentation">
        <button class="nav-link active" id="stores-tab" data-bs-toggle="tab" data-bs-target="#stores" type="button" role="tab">المستودعات</button>
    </li>
    <li class="nav-item" role="presentation">
        <button class="nav-link" id="categories-tab" data-bs-toggle="tab" data-bs-target="#categories" type="button" role="tab">التصنيفات</button>
    </li>
</ul>

<div class="tab-content" id="stockSettingsContent">
    <!-- Stores Tab -->
    <div class="tab-pane fade show active" id="stores" role="tabpanel">
        <div class="d-flex justify-content-between mb-3">
            <h5 class="fw-bold">قائمة المستودعات</h5>
            <?php if (canAdd('stock_settings')): ?>
            <button class="btn btn-primary btn-sm" onclick="openModal('store', 'add')">
                <i class="fas fa-plus"></i> إضافة مستودع
            </button>
            <?php endif; ?>
        </div>
        <div class="card shadow-sm border-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th>#</th>
                            <th>اسم المستودع</th>
                            <th>الموقع / العنوان</th>
                            <th>تاريخ الإضافة</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($stores as $s): ?>
                            <tr>
                                <td><?= $s['id'] ?></td>
                                <td class="fw-bold"><?= htmlspecialchars($s['name']) ?></td>
                                <td><?= htmlspecialchars($s['location'] ?? '-') ?></td>
                                <td><?= date('Y-m-d', strtotime($s['created_at'])) ?></td>
                                <td>
                                    <?php if (canEdit('stock_settings')): ?>
                                    <button class="btn btn-sm btn-outline-primary" onclick='openModal("store", "edit", <?= json_encode($s) ?>)'>
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <?php endif; ?>
                                    <?php if (canDelete('stock_settings')): ?>
                                    <button class="btn btn-sm btn-outline-danger" onclick="confirmDelete('store', <?= $s['id'] ?>)">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Categories Tab -->
    <div class="tab-pane fade" id="categories" role="tabpanel">
        <div class="d-flex justify-content-between mb-3">
            <h5 class="fw-bold">تصنيفات المواد</h5>
            <?php if (canAdd('stock_settings')): ?>
            <button class="btn btn-primary btn-sm" onclick="openModal('category', 'add')">
                <i class="fas fa-plus"></i> إضافة تصنيف
            </button>
            <?php endif; ?>
        </div>
        <div class="card shadow-sm border-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle mb-0">
                    <thead class="bg-light">
                        <tr>
                            <th>#</th>
                            <th>اسم التصنيف</th>
                            <th>الوصف</th>
                            <th>تاريخ الإضافة</th>
                            <th>الإجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($categories as $c): ?>
                            <tr>
                                <td><?= $c['id'] ?></td>
                                <td class="fw-bold"><?= htmlspecialchars($c['name']) ?></td>
                                <td><?= htmlspecialchars($c['description'] ?? '-') ?></td>
                                <td><?= date('Y-m-d', strtotime($c['created_at'])) ?></td>
                                <td>
                                    <?php if (canEdit('stock_settings')): ?>
                                    <button class="btn btn-sm btn-outline-primary" onclick='openModal("category", "edit", <?= json_encode($c) ?>)'>
                                        <i class="fas fa-edit"></i>
                                    </button>
                                    <?php endif; ?>
                                    <?php if (canDelete('stock_settings')): ?>
                                    <button class="btn btn-sm btn-outline-danger" onclick="confirmDelete('category', <?= $c['id'] ?>)">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Generic Modal -->
<div class="modal fade" id="settingsModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-light">
                <h5 class="modal-title" id="modalTitle">إضافة</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" id="modalAction" value="add">
                    <input type="hidden" name="type" id="modalType" value="">
                    <input type="hidden" name="id" id="modalId" value="">
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">الاسم <span class="text-danger">*</span></label>
                        <input type="text" name="name" id="modalName" class="form-control" required>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold" id="descLabel">الوصف / الموقع</label>
                        <textarea name="description" id="modalDesc" class="form-control" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
                    <button type="submit" class="btn btn-primary">حفظ</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    let settingsModal;
    document.addEventListener('DOMContentLoaded', function() {
        settingsModal = new bootstrap.Modal(document.getElementById('settingsModal'));
    });

    function openModal(type, action, data = null) {
        document.getElementById('modalType').value = type;
        document.getElementById('modalAction').value = action;
        
        const typeName = type === 'store' ? 'مستودع' : 'تصنيف';
        document.getElementById('modalTitle').textContent = (action === 'add' ? 'إضافة ' : 'تعديل ') + typeName;
        document.getElementById('descLabel').textContent = type === 'store' ? 'الموقع / العنوان' : 'الوصف';
        
        if (action === 'edit' && data) {
            document.getElementById('modalId').value = data.id;
            document.getElementById('modalName').value = data.name;
            document.getElementById('modalDesc').value = (type === 'store' ? data.location : data.description) || '';
        } else {
            document.getElementById('modalId').value = '';
            document.getElementById('modalName').value = '';
            document.getElementById('modalDesc').value = '';
        }
        settingsModal.show();
    }

    function confirmDelete(type, id) {
        if(confirm('هل أنت متأكد من الحذف؟')) {
            const form = document.createElement('form');
            form.method = 'POST';
            form.innerHTML = `<input type="hidden" name="action" value="delete">
                              <input type="hidden" name="type" value="${type}">
                              <input type="hidden" name="id" value="${id}">`;
            document.body.appendChild(form);
            form.submit();
        }
    }
</script>

<?php require_once __DIR__ . '/includes/footer.php'; ?>
