<?php
// تفعيل عرض الأخطاء لغرض التطوير
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$pageTitle = 'عرض تفاصيل الصرفية';
include '../../includes/header.php';
checkLogin();

// **التحقق من علامة viewport**
// تأكد أن ملف includes/header.php يحتوي على السطر التالي في وسم <head> لضمان التجاوب على الموبايل:
// <meta name="viewport" content="width=device-width, initial-scale=1">

$db = getDB();
$userId = $_SESSION['user_id'] ?? null;

// التحقق من معرف الصرفية
$expenseId = $_GET['id'] ?? null;
if (!$expenseId) {
    $_SESSION['error_message'] = "لم يتم تحديد معرف الصرفية.";
    header("Location: index.php");
    exit;
}

$expense = null;
try {
    $sql = "
        SELECT 
            e.*,
            emp.full_name AS employee_name,
            u_created.full_name AS created_by_name,
            u_approved.full_name AS approved_by_name
        FROM expenses AS e
        LEFT JOIN employees AS emp ON e.employee_id = emp.id
        LEFT JOIN users AS u_created ON e.created_by = u_created.id
        LEFT JOIN users AS u_approved ON e.approved_by = u_approved.id
        WHERE e.id = ?
    ";
    $expense = $db->selectOne($sql, [$expenseId]);

    if (!$expense || (!hasPermission('view_all_expenses') && $expense['created_by'] != $userId)) {
        $_SESSION['error_message'] = "الصرفية المطلوبة غير موجودة أو ليس لديك صلاحية لعرضها.";
        header("Location: index.php");
        exit;
    }
} catch (PDOException $e) {
    error_log("Database error: " . $e->getMessage());
    $_SESSION['error_message'] = 'حدث خطأ أثناء جلب تفاصيل الصرفية.';
    header("Location: index.php");
    exit;
}

// دوال مساعدة (بدون تغيير)
function translateStatus($status) {
    return match($status) {
        'pending' => 'قيد الانتظار',
        'approved' => 'موافق عليه',
        'rejected' => 'مرفوض',
        default => $status,
    };
}

function getStatusBadgeClass($status) {
    return match($status) {
        'approved' => 'bg-success',
        'rejected' => 'bg-danger',
        default => 'bg-warning text-dark',
    };
}

function getExpenseTypeBadgeClass($type) {
    $lowerType = strtolower($type);
    return match($lowerType) {
        'سلفة' => 'bg-info',
        'تعزيز' => 'bg-primary',
        'وقود' => 'bg-secondary',
        'صيانة' => 'bg-dark',
        'رواتب' => 'bg-danger',
        'نثريات' => 'bg-success',
        'مستلزمات مكتبية' => 'bg-warning text-dark',
        default => 'bg-light text-dark',
    };
}

// معالجة المرفق (بدون تغيير)
$receiptExists = false;
$receiptPathForUrl = '';
$receiptIsImage = false;
if (!empty($expense['receipt_path'])) {
    $fullPath = __DIR__ . '/../../' . $expense['receipt_path'];
    $receiptPathForUrl = '../../' . $expense['receipt_path'];

    if (file_exists($fullPath)) {
        $receiptExists = true;
        $mimeType = mime_content_type($fullPath);
        $receiptIsImage = str_contains($mimeType, 'image/');
    }
}
?>

<div class="container py-4">
 <div class="d-flex flex-column flex-md-row gap-2 mb-4">
    <?php if ($expense['status'] === 'pending' && hasPermission('approve_expenses')): ?>
        <a href="approve.php?id=<?php echo $expense['id']; ?>&status=approved" class="btn btn-success w-100 w-md-auto">
            <i class="fas fa-check me-2"></i>موافقة
        </a>
        <a href="approve.php?id=<?php echo $expense['id']; ?>&status=rejected" class="btn btn-danger w-100 w-md-auto">
            <i class="fas fa-times me-2"></i>رفض
        </a>
    <?php endif; ?>

    <?php if (($expense['status'] === 'approved' || $expense['status'] === 'rejected') && hasPermission('revert_approved_expense')): ?>
        <a href="approve.php?id=<?php echo $expense['id']; ?>&status=pending" class="btn btn-warning w-100 w-md-auto">
            <i class="fas fa-undo me-2"></i>إلغاء
        </a>
    <?php endif; ?>

    <?php if ($expense['status'] === 'pending' && (hasPermission('edit_expense') || $expense['created_by'] == $userId)): ?>
        <a href="edit.php?id=<?php echo $expense['id']; ?>" class="btn btn-primary w-100 w-md-auto">
            <i class="fas fa-edit me-2"></i>تعديل
        </a>
    <?php endif; ?>

    <?php if ($expense['status'] === 'pending' && (hasPermission('delete_expense') || $expense['created_by'] == $userId)): ?>
        <a href="delete.php?id=<?php echo $expense['id']; ?>" class="btn btn-danger w-100 w-md-auto" onclick="return confirm('هل أنت متأكد من حذف هذه الصرفية؟');">
            <i class="fas fa-trash me-2"></i>حذف
        </a>
    <?php endif; ?>

    <a href="index.php" class="btn btn-secondary w-100 w-md-auto">
        <i class="fas fa-arrow-right me-2"></i>العودة
    </a>
</div>

    <?php include '../../includes/alerts.php'; ?>

    <?php if ($expense): ?>
        <div class="card shadow-sm mb-4">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-4 pb-4 border-bottom">
                    <h5 class="mb-0">
                        <span class="badge rounded-pill <?php echo getStatusBadgeClass($expense['status']); ?>">
                            <?php echo translateStatus($expense['status']); ?>
                        </span>
                    </h5>
                    <span class="text-muted **text-end**"><i class="fas fa-calendar-alt me-2"></i>تاريخ الصرف: <?php echo htmlspecialchars($expense['expense_date'] ?? 'غير محدد'); ?></span>
                </div>

                <ul class="list-group list-group-flush">
                    
                    <li class="list-group-item d-flex **flex-column flex-md-row** justify-content-between **align-items-start** py-3">
                        <span class="fw-bold text-muted **mb-1 mb-md-0**"><i class="fas fa-tag me-2"></i>نوع الصرف</span>
                        <span><span class="badge <?php echo getExpenseTypeBadgeClass($expense['expense_type']); ?>"><?php echo htmlspecialchars($expense['expense_type'] ?? 'غير محدد'); ?></span></span>
                    </li>
                    
                    <li class="list-group-item d-flex **flex-column flex-md-row** justify-content-between **align-items-start** py-3">
                        <span class="fw-bold text-muted **mb-1 mb-md-0**"><i class="fas fa-list-alt me-2"></i>فئة الصرف</span>
                        <span>
                            <?php 
                            if (!empty($expense['category_id'])) {
                                // جلب اسم الفئة
                                $category = $db->selectOne("SELECT category_name FROM expense_categories WHERE id = ?", [$expense['category_id']]);
                                echo htmlspecialchars($category['category_name'] ?? 'غير محدد');
                            } else {
                                echo 'غير محدد';
                            }
                            ?>
                        </span>
                    </li>


                    <li class="list-group-item d-flex **flex-column flex-md-row** justify-content-between **align-items-start** py-3">
                        <span class="fw-bold text-muted **mb-1 mb-md-0**"><i class="fas fa-user-circle me-2"></i>الموظف المستفيد</span>
                        <span><?php echo htmlspecialchars($expense['employee_name'] ?? 'غير محدد'); ?></span>
                    </li>

                    <li class="list-group-item d-flex **flex-column flex-md-row** justify-content-between **align-items-start** py-3">
                        <span class="fw-bold text-muted **mb-1 mb-md-0**"><i class="fas fa-user-tag me-2"></i>المسؤول عن الصرف</span>
                        <span><?php echo htmlspecialchars($expense['created_by_name'] ?? 'غير معروف'); ?></span>
                    </li>

                    <li class="list-group-item d-flex **flex-column flex-md-row** justify-content-between **align-items-start** py-3">
                        <span class="fw-bold text-muted **mb-1 mb-md-0**"><i class="fas fa-money-bill-wave me-2"></i>المبلغ</span>
                        <span class="fs-5 text-primary"><?php echo number_format($expense['amount'], 2); ?> د.ع</span>
                    </li>

                    <li class="list-group-item d-flex **flex-column flex-md-row** justify-content-between **align-items-start** py-3">
                        <span class="fw-bold text-muted **mb-1 mb-md-0**"><i class="fas fa-check-circle me-2"></i>الموافق</span>
                        <span><?php echo htmlspecialchars($expense['approved_by_name'] ?? 'لم يتم الموافقة بعد'); ?></span>
                    </li>

                    <li class="list-group-item py-3">
                        <div class="fw-bold text-muted mb-2"><i class="fas fa-info-circle me-2"></i>الملاحظات</div>
                        <p class="bg-light p-3 rounded-3 text-secondary">
                            <?php echo nl2br(htmlspecialchars($expense['notes'] ?? 'لا توجد ملاحظات.')); ?>
                        </p>
                    </li>
                </ul>
            </div>
        </div>

        <?php if ($receiptExists): ?>
            <div class="card shadow-sm">
                <div class="card-body">
                    <div class="fw-bold text-muted mb-3"><i class="fas fa-receipt me-2"></i>إيصال الصرفية</div>
                    <?php if ($receiptIsImage): ?>
                        <div class="text-center">
                            <a href="<?php echo htmlspecialchars($receiptPathForUrl); ?>" target="_blank">
                                <img src="<?php echo htmlspecialchars($receiptPathForUrl); ?>" class="img-fluid rounded shadow-sm" alt="إيصال الصرفية">
                            </a>
                        </div>
                    <?php else: ?>
                        <a href="<?php echo htmlspecialchars($receiptPathForUrl); ?>" target="_blank" class="btn btn-outline-primary w-100">
                            <i class="fas fa-file-download me-2"></i>عرض/تحميل المرفق
                        </a>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    <?php else: ?>
        <div class="alert alert-danger text-center" role="alert">
            لا يمكن العثور على الصرفية.
        </div>
    <?php endif; ?>
</div>

<?php
include '../../includes/footer.php';
?>