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

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

// Stats
$total_items = db()->query("SELECT COUNT(*) FROM stock_items")->fetchColumn();
$total_stores = db()->query("SELECT COUNT(*) FROM stock_stores")->fetchColumn();
$low_stock_count = db()->query("
    SELECT COUNT(*) FROM stock_quantities q 
    JOIN stock_items i ON q.item_id = i.id 
    WHERE q.quantity <= i.min_quantity
")->fetchColumn();

// Recent Transactions
$stmt = db()->query("
    SELECT t.*, i.name as item_name, s.name as store_name, u.full_name as user_name
    FROM stock_transactions t
    JOIN stock_items i ON t.item_id = i.id
    JOIN stock_stores s ON t.store_id = s.id
    LEFT JOIN users u ON t.user_id = u.id
    ORDER BY t.created_at DESC LIMIT 10
");
$recent_transactions = $stmt->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 class="btn-toolbar mb-2 mb-md-0">
        <?php if (canView('stock_in')): ?>
        <a href="stock_in.php" class="btn btn-sm btn-success me-2">
            <i class="fas fa-plus"></i> توريد جديد
        </a>
        <?php endif; ?>
        <?php if (canView('stock_out')): ?>
        <a href="stock_out.php" class="btn btn-sm btn-danger">
            <i class="fas fa-minus"></i> صرف جديد
        </a>
        <?php endif; ?>
    </div>
</div>

<div class="row">
    <div class="col-md-4 mb-4">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0 bg-primary bg-opacity-10 p-3 rounded">
                        <i class="fas fa-box fa-2x text-primary"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h6 class="text-muted mb-1">إجمالي الأصناف</h6>
                        <h3 class="mb-0 fw-bold"><?= number_format($total_items) ?></h3>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-4">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0 bg-success bg-opacity-10 p-3 rounded">
                        <i class="fas fa-warehouse fa-2x text-success"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h6 class="text-muted mb-1">المستودعات</h6>
                        <h3 class="mb-0 fw-bold"><?= number_format($total_stores) ?></h3>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="col-md-4 mb-4">
        <div class="card shadow-sm border-0 h-100">
            <div class="card-body">
                <div class="d-flex align-items-center">
                    <div class="flex-shrink-0 bg-warning bg-opacity-10 p-3 rounded">
                        <i class="fas fa-exclamation-triangle fa-2x text-warning"></i>
                    </div>
                    <div class="flex-grow-1 ms-3">
                        <h6 class="text-muted mb-1">تنبيهات المخزون المنخفض</h6>
                        <h3 class="mb-0 fw-bold"><?= number_format($low_stock_count) ?></h3>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card shadow-sm border-0 mb-4">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0 fw-bold"><i class="fas fa-history me-2 text-secondary"></i> أحدث الحركات</h5>
    </div>
    <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>
                    <th>بواسطة</th>
                    <th>التاريخ</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($recent_transactions)): ?>
                <tr>
                    <td colspan="7" class="text-center py-4 text-muted">لا توجد حركات حديثة</td>
                </tr>
                <?php else: ?>
                    <?php foreach ($recent_transactions as $t): ?>
                        <tr>
                            <td><?= $t['id'] ?></td>
                            <td>
                                <?php
                                $badges = [
                                    'in' => ['bg-success', 'توريد'],
                                    'out' => ['bg-danger', 'صرف'],
                                    'damage' => ['bg-dark', 'تالف'],
                                    'lend' => ['bg-info text-dark', 'إعارة'],
                                    'return' => ['bg-primary', 'إرجاع'],
                                    'transfer' => ['bg-secondary', 'نقل']
                                ];
                                $b = $badges[$t['transaction_type']] ?? ['bg-secondary', $t['transaction_type']];
                                ?>
                                <span class="badge <?= $b[0] ?>"><?= $b[1] ?></span>
                            </td>
                            <td class="fw-bold"><?= htmlspecialchars($t['item_name']) ?></td>
                            <td><?= htmlspecialchars($t['store_name']) ?></td>
                            <td dir="ltr" class="text-end fw-bold"><?= number_format($t['quantity'], 2) ?></td>
                            <td><?= htmlspecialchars($t['user_name'] ?? '-') ?></td>
                            <td><?= date('Y-m-d H:i', strtotime($t['created_at'])) ?></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

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