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

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

$start_date = $_GET['start_date'] ?? date('Y-m-01');
$end_date = $_GET['end_date'] ?? date('Y-m-d');
$store_id = $_GET['store_id'] ?? '';
$item_id = $_GET['item_id'] ?? '';
$type = $_GET['type'] ?? '';

// Build Query
$sql = "
    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
    WHERE DATE(t.created_at) BETWEEN ? AND ?
";
$params = [$start_date, $end_date];

if ($store_id) {
    $sql .= " AND t.store_id = ?";
    $params[] = $store_id;
}
if ($item_id) {
    $sql .= " AND t.item_id = ?";
    $params[] = $item_id;
}
if ($type) {
    $sql .= " AND t.transaction_type = ?";
    $params[] = $type;
}

$sql .= " ORDER BY t.created_at DESC";

$stmt = db()->prepare($sql);
$stmt->execute($params);
$transactions = $stmt->fetchAll();

$stores = db()->query("SELECT * FROM stock_stores ORDER BY name ASC")->fetchAll();
$items = db()->query("SELECT * FROM stock_items 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 d-print-none">
    <h1 class="h2">تقارير حركة المخزون</h1>
    <button onclick="window.print()" class="btn btn-secondary">
        <i class="fas fa-print me-2"></i> طباعة التقرير
    </button>
</div>

<div class="card shadow-sm border-0 mb-4 d-print-none">
    <div class="card-body bg-light">
        <form method="GET" class="row g-3">
            <div class="col-md-3">
                <label class="form-label fw-bold">من تاريخ</label>
                <input type="date" name="start_date" class="form-control" value="<?= $start_date ?>">
            </div>
            <div class="col-md-3">
                <label class="form-label fw-bold">إلى تاريخ</label>
                <input type="date" name="end_date" class="form-control" value="<?= $end_date ?>">
            </div>
            <div class="col-md-2">
                <label class="form-label fw-bold">المستودع</label>
                <select name="store_id" class="form-select">
                    <option value="">الكل</option>
                    <?php foreach ($stores as $s): ?>
                        <option value="<?= $s['id'] ?>" <?= $store_id == $s['id'] ? 'selected' : '' ?>><?= htmlspecialchars($s['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label fw-bold">الصنف</label>
                <select name="item_id" class="form-select">
                    <option value="">الكل</option>
                    <?php foreach ($items as $i): ?>
                        <option value="<?= $i['id'] ?>" <?= $item_id == $i['id'] ? 'selected' : '' ?>><?= htmlspecialchars($i['name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button type="submit" class="btn btn-primary w-100">
                    <i class="fas fa-filter me-2"></i> عرض
                </button>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm border-0">
    <div class="card-body p-4">
        <div class="d-none d-print-block text-center mb-4">
            <h3>تقرير حركة المخزون</h3>
            <p>من <?= $start_date ?> إلى <?= $end_date ?></p>
        </div>

        <div class="table-responsive">
            <table class="table table-bordered align-middle mb-0">
                <thead class="bg-light">
                    <tr>
                        <th>#</th>
                        <th>التاريخ</th>
                        <th>النوع</th>
                        <th>المستودع</th>
                        <th>الصنف</th>
                        <th>الكمية</th>
                        <th>المستخدم</th>
                        <th>ملاحظات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($transactions)): ?>
                    <tr>
                        <td colspan="8" class="text-center py-4 text-muted">لا توجد بيانات للعرض</td>
                    </tr>
                    <?php else: ?>
                        <?php foreach ($transactions as $t): ?>
                            <tr>
                                <td><?= $t['id'] ?></td>
                                <td><?= date('Y-m-d H:i', strtotime($t['created_at'])) ?></td>
                                <td>
                                    <?php
                                    $types = [
                                        'in' => 'توريد',
                                        'out' => 'صرف',
                                        'damage' => 'تالف',
                                        'lend' => 'إعارة',
                                        'return' => 'إرجاع',
                                        'transfer' => 'نقل'
                                    ];
                                    echo $types[$t['transaction_type']] ?? $t['transaction_type'];
                                    ?>
                                </td>
                                <td><?= htmlspecialchars($t['store_name']) ?></td>
                                <td class="fw-bold"><?= htmlspecialchars($t['item_name']) ?></td>
                                <td dir="ltr" class="text-end fw-bold">
                                    <?php if ($t['transaction_type'] == 'in' || $t['transaction_type'] == 'return'): ?>
                                        <span class="text-success">+<?= number_format($t['quantity'], 2) ?></span>
                                    <?php else: ?>
                                        <span class="text-danger">-<?= number_format($t['quantity'], 2) ?></span>
                                    <?php endif; ?>
                                </td>
                                <td><?= htmlspecialchars($t['user_name'] ?? '-') ?></td>
                                <td class="small text-muted">
                                    <?php if ($t['reference']): ?>
                                        <strong>المرجع:</strong> <?= htmlspecialchars($t['reference']) ?><br>
                                    <?php endif; ?>
                                    <?= htmlspecialchars($t['notes'] ?? '') ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<style>
    @media print {
        .btn, .sidebar, .top-navbar, form { display: none !important; }
        .main-content { margin: 0 !important; padding: 0 !important; }
        .card { border: none !important; box-shadow: none !important; }
    }
</style>

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