<?php
// -----------------------------------------------------------
// إعدادات التطوير والأمان الأساسية
// -----------------------------------------------------------
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

$pageTitle = 'قائمة الصرفيات';
include '../../includes/header.php';
checkLogin();
$db = getDB();
$userId = $_SESSION['user_id'] ?? null;

// -----------------------------------------------------------
// دوال مساعدة
// -----------------------------------------------------------
function translateStatus($status) {
    switch ($status) {
        case 'pending': return 'قيد الانتظار';
        case 'approved': return 'موافق عليه';
        case 'rejected': return 'مرفوض';
        default: return $status;
    }
}

function getStatusBadgeClass($status) {
    switch ($status) {
        case 'approved': return 'bg-success';
        case 'rejected': return 'bg-danger';
        default: return 'bg-warning text-dark';
    }
}

function buildPaginationLink($page, $filters) {
    unset($filters['page']);
    return "index.php?" . http_build_query(array_merge($filters, ['page' => $page]));
}

// -----------------------------------------------------------
// معالجة الفلاتر وتقسيم الصفحات
// -----------------------------------------------------------
$filters = $_GET;
$page = isset($filters['page']) && is_numeric($filters['page']) ? (int)$filters['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$sqlConditions = [];
$params = [];

if (!hasPermission('view_all_expenses')) {
    $sqlConditions[] = "e.created_by = ?";
    $params[] = $userId;
}

// الفلاتر
if (!empty($filters['status'] ?? null)) {
    $sqlConditions[] = "e.status = ?";
    $params[] = $filters['status'];
}
if (!empty($filters['type'] ?? null)) {
    $sqlConditions[] = "e.expense_type = ?";
    $params[] = $filters['type'];
}
if (!empty($filters['category_id'] ?? null)) {
    $sqlConditions[] = "e.category_id = ?";
    $params[] = $filters['category_id'];
}
if (!empty($filters['employee_name'] ?? null)) {
    $sqlConditions[] = "beneficiary.full_name LIKE ?";
    $params[] = "%{$filters['employee_name']}%";
}
if (!empty($filters['date_from'] ?? null)) {
    $sqlConditions[] = "DATE(e.created_at) >= ?";
    $params[] = $filters['date_from'];
}
if (!empty($filters['date_to'] ?? null)) {
    $sqlConditions[] = "DATE(e.created_at) <= ?";
    $params[] = $filters['date_to'];
}

if (!empty($filters['category_id'] ?? null)) {
    $sqlConditions[] = "e.category_id = ?";
    $params[] = $filters['category_id'];
}


$where = "WHERE 1=1" . (empty($sqlConditions) ? "" : " AND " . implode(" AND ", $sqlConditions));

// -----------------------------------------------------------
// جلب الموظفين والتصنيفات
// -----------------------------------------------------------
$creators = $db->select("SELECT id, full_name FROM users ORDER BY full_name ASC");
$categories = $db->select("SELECT id, category_name FROM expense_categories ORDER BY category_name ASC");

// -----------------------------------------------------------
// جلب الإحصائيات الجديدة
// -----------------------------------------------------------
$stats = [
    'approved_count' => 0,
    'approved_total' => 0,
    'unapproved_count' => 0,
    'unapproved_total' => 0,
    'total_count' => 0
];

try {
    // إجمالي عدد الصرفيات
    $r = $db->selectOne("
        SELECT COUNT(*) AS total_count
        FROM expenses e
        LEFT JOIN users beneficiary ON e.employee_id = beneficiary.employee_id
        {$where}
    ", $params);
    $stats['total_count'] = $r['total_count'] ?? 0;

    // عدد وإجمالي الصرفيات الموافق عليها
    $r = $db->selectOne("
        SELECT COUNT(*) AS approved_count, COALESCE(SUM(amount),0) AS approved_total
        FROM expenses e
        LEFT JOIN users beneficiary ON e.employee_id = beneficiary.employee_id
        {$where} AND e.status='approved'
    ", $params);
    $stats['approved_count'] = $r['approved_count'] ?? 0;
    $stats['approved_total'] = $r['approved_total'] ?? 0;

    // عدد وإجمالي الصرفيات غير الموافق عليها
    $r = $db->selectOne("
        SELECT COUNT(*) AS unapproved_count, COALESCE(SUM(amount),0) AS unapproved_total
        FROM expenses e
        LEFT JOIN users beneficiary ON e.employee_id = beneficiary.employee_id
        {$where} AND e.status!='approved'
    ", $params);
    $stats['unapproved_count'] = $r['unapproved_count'] ?? 0;
    $stats['unapproved_total'] = $r['unapproved_total'] ?? 0;

} catch (PDOException $e) {
    $_SESSION['error_message'] = 'حدث خطأ أثناء جلب الإحصائيات.';
}

// -----------------------------------------------------------
// جلب الصرفيات مع المستفيد
// -----------------------------------------------------------
$totalFilteredExpenses = $stats['total_count'];
$totalPages = ceil($totalFilteredExpenses / $limit);

$sql = "
    SELECT e.id, e.title, e.amount, e.status, e.created_at, e.created_by, e.expense_type, ec.category_name,
           user_created.full_name AS created_by_name,
           user_approved.full_name AS approved_by_name,
           beneficiary.full_name AS employee_name
    FROM expenses e
    LEFT JOIN expense_categories ec ON e.category_id = ec.id
    LEFT JOIN users user_created ON e.created_by = user_created.id
    LEFT JOIN users user_approved ON e.approved_by = user_approved.id
    LEFT JOIN users beneficiary ON e.employee_id = beneficiary.employee_id
    {$where} ORDER BY e.created_at DESC
    LIMIT ? OFFSET ?
";
try {
    $expenses = $db->select($sql, array_merge($params, [$limit, $offset]));
} catch (PDOException $e) {
    $_SESSION['error_message'] = 'خطأ في قاعدة البيانات.';
}

// -----------------------------------------------------------
// نهاية PHP، بدء HTML
// -----------------------------------------------------------
?>
<div class="container py-4">
    <h1 class="text-center mb-5"><?= htmlspecialchars($pageTitle) ?></h1>

    <!-- الإحصائيات -->
    <div class="row row-cols-1 row-cols-md-4 g-4 mb-4">
        <div class="col">
            <div class="card text-white bg-success h-100">
                <div class="card-body">
                    <h5 class="card-title mb-0">الصرفيات الموافق عليها</h5>
                    <div class="fs-6 mt-3">
                        عدد: <?= $stats['approved_count'] ?><br>
                        المجموع: <?= number_format($stats['approved_total'],2) ?> د.ع
                    </div>
                </div>
            </div>
        </div>

        <div class="col">
            <div class="card text-white bg-danger h-100">
                <div class="card-body">
                    <h5 class="card-title mb-0">الصرفيات الغير موافق عليها</h5>
                    <div class="fs-6 mt-3">
                        عدد: <?= $stats['unapproved_count'] ?><br>
                        المجموع: <?= number_format($stats['unapproved_total'],2) ?> د.ع
                    </div>
                </div>
            </div>
        </div>

        <div class="col">
            <div class="card text-white bg-info h-100">
                <div class="card-body">
                    <h5 class="card-title mb-0">إجمالي عدد الصرفيات</h5>
                    <div class="fs-6 mt-3"><?= $stats['total_count'] ?></div>
                </div>
            </div>
        </div>
    </div>

    <!-- نموذج الفلاتر -->
    <div class="card shadow-sm mb-4">
        <div class="card-body">
            <form method="get" class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label>العنوان</label>
                    <input type="text" name="title" class="form-control" value="<?= htmlspecialchars($filters['title'] ?? '') ?>">
                </div>

                <div class="col-md-3">
                    <label>الحالة</label>
                    <select name="status" class="form-select">
                        <option value="">كل الحالات</option>
                        <option value="pending" <?= ($filters['status'] ?? '')==='pending'?'selected':'' ?>>قيد الانتظار</option>
                        <option value="approved" <?= ($filters['status'] ?? '')==='approved'?'selected':'' ?>>موافق عليه</option>
                        <option value="rejected" <?= ($filters['status'] ?? '')==='rejected'?'selected':'' ?>>مرفوض</option>
                    </select>
                </div>
                
                <div class="col-md-3">
    <label>التصنيف</label>
    <select name="category_id" class="form-select">
        <option value="">كل التصنيفات</option>
        <?php foreach($categories as $c): ?>
            <option value="<?= $c['id'] ?>" <?= (string)($filters['category_id'] ?? '') === (string)$c['id'] ? 'selected':'' ?>>
                <?= htmlspecialchars($c['category_name']) ?>
            </option>
        <?php endforeach; ?>
    </select>
</div>


                <div class="col-md-3">
                    <label>نوع الصرف</label>
                    <select name="type" class="form-select">
                        <option value="">كل الأنواع</option>
                        <option value="تعزيز" <?= ($filters['type'] ?? '')==='تعزيز'?'selected':'' ?>>تعزيز</option>
                        <option value="سلفة" <?= ($filters['type'] ?? '')==='سلفة'?'selected':'' ?>>سلف</option>
                    </select>
                </div>

                <div class="col-md-3">
                    <label>التصنيف</label>
                    <select name="category_id" class="form-select">
                        <option value="">كل التصنيفات</option>
                        <?php foreach($categories as $c): ?>
                            <option value="<?= $c['id'] ?>" <?= (string)($filters['category_id'] ?? '') === (string)$c['id'] ? 'selected':'' ?>>
                                <?= htmlspecialchars($c['category_name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-md-3">
                    <label>المسؤول</label>
                    <input type="text" name="employee_name" class="form-control" value="<?= htmlspecialchars($filters['employee_name'] ?? '') ?>">
                </div>

                <div class="col-md-3">
                    <label>من تاريخ</label>
                    <input type="date" name="date_from" class="form-control" value="<?= htmlspecialchars($filters['date_from'] ?? '') ?>">
                </div>

                <div class="col-md-3">
                    <label>إلى تاريخ</label>
                    <input type="date" name="date_to" class="form-control" value="<?= htmlspecialchars($filters['date_to'] ?? '') ?>">
                </div>

                <div class="col-12 text-end">
                    <button type="submit" class="btn btn-primary me-2"><i class="fas fa-search me-2"></i>بحث</button>
                    <a href="index.php" class="btn btn-secondary"><i class="fas fa-eraser me-2"></i>إعادة تعيين</a>
                </div>
            </form>
        </div>
    </div>

    <!-- جدول الصرفيات -->
    <div class="card shadow-sm">
        <div class="card-body">
            <?php include '../../includes/alerts.php'; ?>
            <?php if(!empty($expenses)): ?>
                <div class="table-responsive">
                    <table class="table table-striped table-hover table-bordered text-center" id="expensesTable">
                        <thead class="table-primary text-white">
                            <tr>
                                <th>العنوان</th>
                                <th>النوع</th>
                                <th>التصنيف</th>
                                <th>المبلغ</th>
                                <th>الحالة</th>
                                <th>المُنشئ</th>
                                <th>المسؤول</th>
                                <th>تاريخ الإنشاء</th>
                                <th>الموافق</th>
                                <th>الإجراءات</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php
                            $canApprove = hasPermission('approve_expenses');
                            $canRevert = hasPermission('revert_approved_expense');
                            $canEdit = hasPermission('edit_expense');
                            $canDelete = hasPermission('delete_expense');

                            foreach($expenses as $e):
                                $isCreator = $e['created_by'] == $userId;
                                $isPending = $e['status'] === 'pending';
                                $isApprovedOrRejected = $e['status'] !== 'pending';
                            ?>
                            <tr>
                                <td><?= htmlspecialchars($e['title']) ?></td>
                                <td><?= htmlspecialchars($e['expense_type'] === 'تعزيز' ? 'تعزيز' : ($e['expense_type']==='سلفة'?'سلف':'أخرى')) ?></td>
                                <td><?= htmlspecialchars($e['category_name'] ?? 'غير مصنف') ?></td>
                                <td><?= number_format($e['amount'],2) ?></td>
                                <td><span class="badge <?= getStatusBadgeClass($e['status']) ?>"><?= translateStatus($e['status']) ?></span></td>
                                <td><?= htmlspecialchars($e['created_by_name'] ?? 'غير معروف') ?></td>
                                <td><?= htmlspecialchars($e['employee_name'] ?? 'غير محدد') ?></td>
                                <td><?= date('Y-m-d', strtotime($e['created_at'])) ?></td>
                                <td><?= htmlspecialchars($e['approved_by_name'] ?? 'غير معتمد') ?></td>
                                <td>
                                    <div class="dropdown">
                                        <button class="btn btn-sm btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown"><i class="fas fa-cog"></i></button>
                                        <ul class="dropdown-menu dropdown-menu-end">
                                            <li><a class="dropdown-item" href="view.php?id=<?= $e['id'] ?>"><i class="fas fa-eye me-2"></i>عرض</a></li>
                                            <?php if($canApprove && $isPending): ?>
                                                <li><hr class="dropdown-divider"></li>
                                                <li><a class="dropdown-item text-success" href="approve.php?id=<?= $e['id'] ?>&status=approved">موافقة</a></li>
                                                <li><a class="dropdown-item text-danger" href="approve.php?id=<?= $e['id'] ?>&status=rejected">رفض</a></li>
                                            <?php endif; ?>
                                            <?php if($canRevert && $isApprovedOrRejected): ?>
                                                <li><a class="dropdown-item text-warning" href="approve.php?id=<?= $e['id'] ?>&status=pending">إلغاء</a></li>
                                            <?php endif; ?>
                                            <?php if($isPending && ($canEdit || $isCreator)): ?>
                                                <li><a class="dropdown-item text-primary" href="edit.php?id=<?= $e['id'] ?>">تعديل</a></li>
                                            <?php endif; ?>
                                            <?php if($isPending && ($canDelete || $isCreator)): ?>
                                                <li><a class="dropdown-item text-danger" href="delete.php?id=<?= $e['id'] ?>" onclick="return confirm('هل أنت متأكد من الحذف؟');">حذف</a></li>
                                            <?php endif; ?>
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>

                <!-- pagination -->
               <?php if($totalPages > 1): ?>
                    <nav class="mt-4">
                        <ul class="pagination justify-content-center">
                            <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                                <a class="page-link" href="<?= buildPaginationLink($page - 1, $filters) ?>">&laquo;</a>
                            </li>

                            <?php 
                            // --- منطق الـ 5 صفحات الذكي ---
                            $max_visible = 5; // عدد الأرقام التي ستظهر في المنتصف
                            
                            // حساب بداية ونهاية النطاق
                            $start = max(1, $page - 2);
                            $end = min($totalPages, $start + $max_visible - 1);

                            // تصحيح البداية إذا وصلنا لنهاية الصفحات
                            if ($end - $start < $max_visible - 1) {
                                $start = max(1, $end - $max_visible + 1);
                            }

                            // عرض رابط الصفحة الأولى إذا كنا بعيدين عنها
                            if ($start > 1): ?>
                                <li class="page-item"><a class="page-link" href="<?= buildPaginationLink(1, $filters) ?>">1</a></li>
                                <?php if ($start > 2): ?>
                                    <li class="page-item disabled"><span class="page-link">...</span></li>
                                <?php endif; ?>
                            <?php endif; ?>

                            <?php 
                            // حلقة عرض الأرقام المحصورة (الـ 5 صفحات)
                            for ($i = $start; $i <= $end; $i++): 
                            ?>
                                <li class="page-item <?= ($page == $i) ? 'active' : '' ?>">
                                    <a class="page-link" href="<?= buildPaginationLink($i, $filters) ?>"><?= $i ?></a>
                                </li>
                            <?php endfor; ?>

                            <?php 
                            // عرض رابط الصفحة الأخيرة إذا كنا بعيدين عنها
                            if ($end < $totalPages): ?>
                                <?php if ($end < $totalPages - 1): ?>
                                    <li class="page-item disabled"><span class="page-link">...</span></li>
                                <?php endif; ?>
                                <li class="page-item"><a class="page-link" href="<?= buildPaginationLink($totalPages, $filters) ?>"><?= $totalPages ?></a></li>
                            <?php endif; ?>

                            <li class="page-item <?= ($page >= $totalPages) ? 'disabled' : '' ?>">
                                <a class="page-link" href="<?= buildPaginationLink($page + 1, $filters) ?>">&raquo;</a>
                            </li>
                        </ul>
                    </nav>
                <?php endif; ?>

            <?php else: ?>
                <div class="alert alert-info text-center">لا توجد صرفيات لعرضها.</div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- CSS للطباعة -->
<style>
@media print {
    .navbar, .footer, .pagination, .action-col, .print-hide-buttons, .alert { display: none !important; }
    .container, .table-responsive { width: 100% !important; max-width: none !important; }
}
</style>

<!-- Export to Excel -->
<script>
function exportTableToExcel(tableID, filename=''){
    var tableSelect = document.getElementById(tableID);
    var tableHtml = tableSelect.outerHTML.replace(/<th[^>]*action-col[^>]*>.*?<\/th>/gi,'').replace(/<td[^>]*action-col[^>]*>.*?<\/td>/gi,'');
    var dataType = 'application/vnd.ms-excel';
    filename = filename ? filename+'.xls' : 'excel_data.xls';
    var downloadLink = document.createElement("a");
    document.body.appendChild(downloadLink);
    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHtml], {type:dataType});
        navigator.msSaveOrOpenBlob(blob, filename);
    } else {
        downloadLink.href = 'data:' + dataType + ', ' + encodeURIComponent(tableHtml);
        downloadLink.download = filename;
        downloadLink.click();
    }
}
</script>

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