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

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

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

// Handle Form Submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $store_id = $_POST['store_id'] ?? null;
    $item_id = $_POST['item_id'] ?? null;
    $quantity = $_POST['quantity'] ?? 0;
    $reference = $_POST['reference'] ?? '';
    $notes = $_POST['notes'] ?? '';

    if ($store_id && $item_id && $quantity > 0) {
        try {
            $pdo = db();
            $pdo->beginTransaction();

            // 1. Create Transaction
            $stmt = $pdo->prepare("INSERT INTO stock_transactions (transaction_type, store_id, item_id, quantity, user_id, reference, notes) VALUES ('in', ?, ?, ?, ?, ?, ?)");
            $stmt->execute([$store_id, $item_id, $quantity, $_SESSION['user_id'], $reference, $notes]);
            
            // 2. Update Quantity
            // Check if record exists
            $check = $pdo->prepare("SELECT id, quantity FROM stock_quantities WHERE store_id = ? AND item_id = ?");
            $check->execute([$store_id, $item_id]);
            $exists = $check->fetch();

            if ($exists) {
                $new_qty = $exists['quantity'] + $quantity;
                $update = $pdo->prepare("UPDATE stock_quantities SET quantity = ? WHERE id = ?");
                $update->execute([$new_qty, $exists['id']]);
            } else {
                $insert = $pdo->prepare("INSERT INTO stock_quantities (store_id, item_id, quantity) VALUES (?, ?, ?)");
                $insert->execute([$store_id, $item_id, $quantity]);
            }

            $pdo->commit();
            $success = 'تم تسجيل عملية التوريد بنجاح';
        } catch (PDOException $e) {
            $pdo->rollBack();
            $error = 'حدث خطأ: ' . $e->getMessage();
        }
    } else {
        $error = 'يرجى تعبئة جميع الحقول المطلوبة';
    }
}

// Fetch Data for Dropdowns
$stores = db()->query("SELECT * FROM stock_stores ORDER BY name ASC")->fetchAll();
$items = db()->query("SELECT * FROM stock_items ORDER BY name ASC")->fetchAll();

// Pagination for History
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$where = "WHERE t.transaction_type = 'in'";
$params = [];

// Count Total
$countQuery = "SELECT COUNT(*) FROM stock_transactions t $where";
$countStmt = db()->prepare($countQuery);
$countStmt->execute($params);
$totalFiltered = $countStmt->fetchColumn();

// Fetch History
$historyQuery = "
    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
    ORDER BY t.created_at DESC
    LIMIT $limit OFFSET $offset
";
$stmt = db()->prepare($historyQuery);
$stmt->execute($params);
$history = $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>
    <a href="stock_dashboard.php" class="btn btn-secondary">
        <i class="fas fa-arrow-right"></i> عودة للوحة التحكم
    </a>
</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; ?>

<div class="row justify-content-center mb-5">
    <div class="col-md-8">
        <div class="card shadow-sm border-0">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0"><i class="fas fa-plus-circle me-2"></i> تسجيل توريد جديد</h5>
            </div>
            <div class="card-body p-4">
                <form method="POST">
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">المستودع <span class="text-danger">*</span></label>
                            <select name="store_id" class="form-select" required>
                                <option value="">-- اختر المستودع --</option>
                                <?php foreach ($stores as $store): ?>
                                    <option value="<?= $store['id'] ?>"><?= htmlspecialchars($store['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">الصنف <span class="text-danger">*</span></label>
                            <select name="item_id" class="form-select" required>
                                <option value="">-- اختر الصنف --</option>
                                <?php foreach ($items as $item): ?>
                                    <option value="<?= $item['id'] ?>"><?= htmlspecialchars($item['name']) ?> (<?= htmlspecialchars($item['sku'] ?: '-') ?>)</option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">الكمية <span class="text-danger">*</span></label>
                            <input type="number" step="0.01" name="quantity" class="form-control" required min="0.01">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label fw-bold">رقم المرجع / الفاتورة</label>
                            <input type="text" name="reference" class="form-control" placeholder="مثال: فاتورة رقم 123">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">ملاحظات</label>
                        <textarea name="notes" class="form-control" rows="3"></textarea>
                    </div>

                    <div class="d-grid">
                        <button type="submit" class="btn btn-success btn-lg">
                            <i class="fas fa-save me-2"></i> حفظ عملية التوريد
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- History Table -->
<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 class="ps-4">#</th>
                    <th>الصنف</th>
                    <th>المستودع</th>
                    <th>الكمية</th>
                    <th>بواسطة</th>
                    <th>التاريخ</th>
                    <th>المرجع</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($history)): ?>
                    <tr>
                        <td colspan="7" class="text-center py-4 text-muted">لا توجد عمليات توريد سابقة.</td>
                    </tr>
                <?php else: ?>
                    <?php foreach ($history as $h): ?>
                        <tr>
                            <td class="ps-4"><?= $h['id'] ?></td>
                            <td class="fw-bold"><?= htmlspecialchars($h['item_name']) ?></td>
                            <td><?= htmlspecialchars($h['store_name']) ?></td>
                            <td class="text-success fw-bold" dir="ltr">+<?= number_format($h['quantity'], 2) ?></td>
                            <td><?= htmlspecialchars($h['user_name'] ?? '-') ?></td>
                            <td><?= date('Y-m-d H:i', strtotime($h['created_at'])) ?></td>
                            <td><small class="text-muted"><?= htmlspecialchars($h['reference'] ?? '-') ?></small></td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <!-- Pagination -->
    <?php renderPagination($page, $totalFiltered, $limit); ?>
</div>

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