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

if (!canView('stock_out')) {
    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;
    $type = $_POST['type'] ?? 'out'; // 'out' or 'damage'
    $reference = $_POST['reference'] ?? '';
    $notes = $_POST['notes'] ?? '';

    if ($store_id && $item_id && $quantity > 0) {
        try {
            $pdo = db();
            // Check availability first
            $check = $pdo->prepare("SELECT id, quantity FROM stock_quantities WHERE store_id = ? AND item_id = ?");
            $check->execute([$store_id, $item_id]);
            $stock = $check->fetch();

            if (!$stock || $stock['quantity'] < $quantity) {
                $error = 'الكمية غير متوفرة في المستودع المحدد. الكمية الحالية: ' . ($stock['quantity'] ?? 0);
            } else {
                $pdo->beginTransaction();

                // 1. Create Transaction
                $stmt = $pdo->prepare("INSERT INTO stock_transactions (transaction_type, store_id, item_id, quantity, user_id, reference, notes) VALUES (?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([$type, $store_id, $item_id, $quantity, $_SESSION['user_id'], $reference, $notes]);
                
                // 2. Update Quantity
                $new_qty = $stock['quantity'] - $quantity;
                $update = $pdo->prepare("UPDATE stock_quantities SET quantity = ? WHERE id = ?");
                $update->execute([$new_qty, $stock['id']]);

                $pdo->commit();
                $success = 'تم تسجيل عملية الصرف بنجاح';
            }
        } catch (PDOException $e) {
            if ($pdo->inTransaction()) $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 ('out', 'damage')";
$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-danger text-white">
                <h5 class="mb-0"><i class="fas fa-minus-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>
                            <select name="type" class="form-select">
                                <option value="out">صرف (استهلاك/بيع)</option>
                                <option value="damage">تالف / منتهي الصلاحية</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">رقم المرجع / للمستلم</label>
                        <input type="text" name="reference" class="form-control" placeholder="مثال: إذن صرف رقم 55">
                    </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-danger btn-lg">
                            <i class="fas fa-sign-out-alt 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>
                    <th>المرجع</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($history)): ?>
                    <tr>
                        <td colspan="8" 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>
                                <?php if ($h['transaction_type'] == 'damage'): ?>
                                    <span class="badge bg-dark">تالف</span>
                                <?php else: ?>
                                    <span class="badge bg-danger">صرف</span>
                                <?php endif; ?>
                            </td>
                            <td class="fw-bold"><?= htmlspecialchars($h['item_name']) ?></td>
                            <td><?= htmlspecialchars($h['store_name']) ?></td>
                            <td class="text-danger 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'; ?>