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

if (!canView('stock_lending')) {
    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'] ?? '';
    
    if ($action === 'lend') {
        $store_id = $_POST['store_id'];
        $item_id = $_POST['item_id'];
        $quantity = $_POST['quantity'];
        $borrower = $_POST['borrower_name'];
        $phone = $_POST['borrower_phone'];
        $date = $_POST['expected_return_date'];
        
        try {
            $pdo = db();
            $pdo->beginTransaction();
            
            // Check stock
            $check = $pdo->prepare("SELECT id, quantity FROM stock_quantities WHERE store_id = ? AND item_id = ? FOR UPDATE");
            $check->execute([$store_id, $item_id]);
            $stock = $check->fetch();
            
            if (!$stock || $stock['quantity'] < $quantity) {
                throw new Exception("الكمية غير متوفرة للإعارة");
            }
            
            // Deduct Stock
            $pdo->prepare("UPDATE stock_quantities SET quantity = quantity - ? WHERE id = ?")->execute([$quantity, $stock['id']]);
            
            // Create Transaction
            $stmt = $pdo->prepare("INSERT INTO stock_transactions (transaction_type, store_id, item_id, quantity, user_id, reference) VALUES ('lend', ?, ?, ?, ?, ?)");
            $stmt->execute([$store_id, $item_id, $quantity, $_SESSION['user_id'], "إعارة: $borrower"]);
            $trans_id = $pdo->lastInsertId();
            
            // Create Lending Record
            $stmt = $pdo->prepare("INSERT INTO stock_lending (transaction_id, borrower_name, borrower_phone, expected_return_date, status) VALUES (?, ?, ?, ?, 'active')");
            $stmt->execute([$trans_id, $borrower, $phone, $date]);
            
            $pdo->commit();
            $success = 'تم تسجيل الإعارة بنجاح';
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = $e->getMessage();
        }
    } elseif ($action === 'return') {
        $lending_id = $_POST['lending_id'];
        
        try {
            $pdo = db();
            $pdo->beginTransaction();
            
            // Get Lending Info
            $lend = $pdo->query("SELECT l.*, t.store_id, t.item_id, t.quantity FROM stock_lending l JOIN stock_transactions t ON l.transaction_id = t.id WHERE l.id = $lending_id")->fetch();
            
            if ($lend && $lend['status'] === 'active') {
                // Add Stock Back
                $check = $pdo->prepare("SELECT id FROM stock_quantities WHERE store_id = ? AND item_id = ?");
                $check->execute([$lend['store_id'], $lend['item_id']]);
                $s_id = $check->fetchColumn();
                
                if ($s_id) {
                    $pdo->prepare("UPDATE stock_quantities SET quantity = quantity + ? WHERE id = ?")->execute([$lend['quantity'], $s_id]);
                } else {
                    $pdo->prepare("INSERT INTO stock_quantities (store_id, item_id, quantity) VALUES (?, ?, ?)")->execute([$lend['store_id'], $lend['item_id'], $lend['quantity']]);
                }
                
                // Create Return Transaction
                $stmt = $pdo->prepare("INSERT INTO stock_transactions (transaction_type, store_id, item_id, quantity, user_id, reference) VALUES ('return', ?, ?, ?, ?, ?)");
                $stmt->execute([$lend['store_id'], $lend['item_id'], $lend['quantity'], $_SESSION['user_id'], "إرجاع إعارة: " . $lend['borrower_name']]);
                $ret_id = $pdo->lastInsertId();
                
                // Update Lending Record
                $pdo->prepare("UPDATE stock_lending SET status = 'returned', return_transaction_id = ? WHERE id = ?")->execute([$ret_id, $lending_id]);
                
                $pdo->commit();
                $success = 'تم إرجاع المواد بنجاح';
            }
        } catch (Exception $e) {
            $pdo->rollBack();
            $error = $e->getMessage();
        }
    }
}

// Fetch Active Loans
$loans = db()->query("
    SELECT l.*, i.name as item_name, s.name as store_name, t.quantity, t.created_at as lend_date
    FROM stock_lending l
    JOIN stock_transactions t ON l.transaction_id = t.id
    JOIN stock_items i ON t.item_id = i.id
    JOIN stock_stores s ON t.store_id = s.id
    WHERE l.status = 'active'
    ORDER BY l.expected_return_date ASC
")->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">
    <h1 class="h2">إعارة المواد</h1>
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#lendModal">
        <i class="fas fa-hand-holding me-2"></i> إعارة جديدة
    </button>
</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="card shadow-sm border-0">
    <div class="card-header bg-white py-3">
        <h5 class="mb-0 fw-bold"><i class="fas fa-clock me-2 text-warning"></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 class="text-secondary text-nowrap" style="font-size: 0.85rem;"><i class="fas fa-user-plus me-1"></i>أضيف بواسطة</th>
                        <th class="text-secondary text-nowrap" style="font-size: 0.85rem;"><i class="fas fa-user-edit me-1"></i>عُدل بواسطة</th>
                        <th>الإجراءات</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($loans)): ?>
                <tr>
                    <td colspan="9" class="text-center py-4 text-muted">لا توجد إعارات نشطة حالياً</td>
                </tr>
                <?php else: ?>
                    <?php foreach ($loans as $loan): ?>
                        <tr>
                            <td class="fw-bold">
                                <?= htmlspecialchars($loan['borrower_name']) ?>
                                <br><small class="text-muted"><?= htmlspecialchars($loan['borrower_phone']) ?></small>
                            </td>
                            <td><?= htmlspecialchars($loan['item_name']) ?></td>
                            <td class="fw-bold"><?= number_format($loan['quantity'], 2) ?></td>
                            <td><?= date('Y-m-d', strtotime($loan['lend_date'])) ?></td>
                            <td>
                                <?php
                                    $due = strtotime($loan['expected_return_date']);
                                    $cls = ($due < time()) ? 'text-danger fw-bold' : '';
                                ?>
                                <span class="<?= $cls ?>"><?= date('Y-m-d', $due) ?></span>
                            </td>
                            <td><span class="badge bg-warning text-dark">نشط</span></td>
                            <td><small class="text-muted"><i class="fas fa-user text-primary opacity-50 me-1"></i><?= htmlspecialchars(getAuditUserName($loan['created_by'] ?? null)) ?></small></td>
                            <td><small class="text-muted"><i class="fas fa-user-edit text-warning opacity-50 me-1"></i><?= htmlspecialchars(getAuditUserName($loan['updated_by'] ?? null)) ?></small></td>
                            <td>
                                <form method="POST" onsubmit="return confirm('هل استلمت المواد المرجعة؟ سيتم إضافتها للمخزون.')">
                                    <input type="hidden" name="action" value="return">
                                    <input type="hidden" name="lending_id" value="<?= $loan['id'] ?>">
                                    <button type="submit" class="btn btn-sm btn-success">
                                        <i class="fas fa-check me-1"></i> تسجيل إرجاع
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Lend Modal -->
<div class="modal fade" id="lendModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title">تسجيل إعارة جديدة</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="lend">
                    
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">المستودع</label>
                            <select name="store_id" class="form-select" required>
                                <?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">المادة</label>
                            <select name="item_id" class="form-select" required>
                                <?php foreach ($items as $item): ?>
                                    <option value="<?= $item['id'] ?>"><?= htmlspecialchars($item['name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">الكمية</label>
                        <input type="number" step="0.01" name="quantity" class="form-control" required>
                    </div>

                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">اسم المستعير</label>
                            <input type="text" name="borrower_name" class="form-control" required>
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">رقم الهاتف</label>
                            <input type="text" name="borrower_phone" class="form-control">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">تاريخ الإرجاع المتوقع</label>
                        <input type="date" name="expected_return_date" class="form-control" required>
                    </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>

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