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

$pageTitle = 'إدارة الصندوق الرئيسي'; 
include '../../includes/header.php'; // 🛑 يجب التأكد من صحة المسار (مستويين)
checkLogin();

$db = getDB();

// =====================
// 🔹 إعداد الترقيم
// =====================
$limit = 20; // 20 صفاً لكل صفحة
$page = $_GET['p'] ?? 1;
$offset = ($page - 1) * $limit;

// =====================
// 🔹 إعداد الفلاتر
// =====================
$filterStartDate = $_GET['start_date'] ?? date('Y-m-01');
$filterEndDate = $_GET['end_date'] ?? date('Y-m-d');
$filterType = $_GET['type'] ?? '';

// ===========================================
// 1. حساب الرصيد الكلي الحالي للصندوق (غير مفلتر بتاريخ)
// ===========================================
$total_in_all = $db->select("SELECT SUM(amount) AS total FROM main_cashbox WHERE transaction_type='دخل'")[0]['total'] ?? 0;
$total_out_all = $db->select("SELECT SUM(amount) AS total FROM main_cashbox WHERE transaction_type='خرج'")[0]['total'] ?? 0;
$balance_current = $total_in_all - $total_out_all;

// ===========================================
// 2. بناء استعلام حركات الصندوق الرئيسي (main_cashbox)
// ===========================================
$cashbox_sql_base = "
SELECT 
    c.id,
    c.transaction_date AS date,
    c.transaction_type AS type,
    c.operation_type,
    c.amount,
    e.full_name AS employee_name,
    u.full_name AS created_by_name,
    c.description
FROM main_cashbox c
LEFT JOIN employees e ON c.employee_id = e.id
LEFT JOIN users u ON c.created_by = u.id
WHERE c.transaction_date BETWEEN ? AND ?
";
$params = [$filterStartDate, $filterEndDate];

// تطبيق فلتر نوع الحركة (إذا تم اختياره)
if ($filterType !== '') {
    $cashbox_sql_base .= " AND c.transaction_type = ?";
    $params[] = $filterType;
}

// 3. حساب عدد الصفوف الكلي لتحديد الترقيم
$count_sql = "SELECT COUNT(*) AS total FROM main_cashbox c 
              LEFT JOIN employees e ON c.employee_id = e.id
              WHERE c.transaction_date BETWEEN ? AND ?";
$count_params = [$filterStartDate, $filterEndDate];

if ($filterType !== '') {
    $count_sql .= " AND c.transaction_type = ?";
    $count_params[] = $filterType;
}

$total_rows_filtered = $db->select($count_sql, $count_params)[0]['total'] ?? 0;
$total_pages = ceil($total_rows_filtered / $limit);

// 4. جلب الصفوف مع تطبيق الترتيب والترقيم
$cashbox_sql = $cashbox_sql_base . " ORDER BY c.transaction_date DESC LIMIT $limit OFFSET $offset";
$rows = $db->select($cashbox_sql, $params) ?: [];


// 5. حساب الإجماليات المفلترة (من قاعدة البيانات لجميع النتائج المفلترة بالتاريخ والنوع)
$summary_sql = "
SELECT 
    SUM(CASE WHEN transaction_type = 'دخل' THEN amount ELSE 0 END) AS total_in,
    SUM(CASE WHEN transaction_type = 'خرج' THEN amount ELSE 0 END) AS total_out
FROM main_cashbox
WHERE transaction_date BETWEEN ? AND ?
";
$summary_params = [$filterStartDate, $filterEndDate];
if ($filterType !== '') {
    $summary_sql .= " AND transaction_type = ?";
    $summary_params[] = $filterType;
}

$summary_results = $db->select($summary_sql, $summary_params)[0];
$total_in_filtered = $summary_results['total_in'] ?? 0;
$total_out_filtered = $summary_results['total_out'] ?? 0;
$net_movement_filtered = $total_in_filtered - $total_out_filtered;

// 🚨 تحديد الصلاحيات المطلوبة
$can_edit = hasPermission('edit_cashbox_entry'); 
$can_delete = hasPermission('delete_cashbox_entry'); 
$can_add = hasPermission('add_cashbox_entry');
?>

<div class="container py-4" dir="rtl">
    <h2 class="text-center mb-4"><i class="fas fa-hand-holding-usd me-2"></i><?= htmlspecialchars($pageTitle) ?></h2>
    
    <div class="row mb-4">
        <div class="col-md-4">
            <div class="card text-white bg-primary shadow-sm">
                <div class="card-body text-center">
                    <h5>**الرصيد الكلي الحالي**</h5>
                    <h3><?= number_format($balance_current, 2) ?> د.ع</h3>
                    <p class="mb-0 text-white-50"><small>(لجميع الفترات)</small></p>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card text-white bg-success shadow-sm">
                <div class="card-body text-center">
                    <h5>إجمالي الدخل (مُفلتر)</h5>
                    <h3><?= number_format($total_in_filtered, 2) ?> د.ع</h3>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card text-white <?= $net_movement_filtered >= 0 ? 'bg-info' : 'bg-warning' ?> shadow-sm">
                <div class="card-body text-center">
                    <h5>صافي الحركة (مُفلتر)</h5>
                    <h3><?= number_format($net_movement_filtered, 2) ?> د.ع</h3>
                </div>
            </div>
        </div>
    </div>

    <form method="GET" class="row g-3 mb-4 p-3 bg-light border rounded shadow-sm">
        <input type="hidden" name="p" value="<?= htmlspecialchars($page) ?>">
        <div class="col-md-4">
            <label class="form-label">من تاريخ</label>
            <input type="date" name="start_date" value="<?= htmlspecialchars($filterStartDate) ?>" class="form-control">
        </div>
        <div class="col-md-4">
            <label class="form-label">إلى تاريخ</label>
            <input type="date" name="end_date" value="<?= htmlspecialchars($filterEndDate) ?>" class="form-control">
        </div>
        <div class="col-md-4">
            <label class="form-label">نوع الحركة</label>
            <select name="type" class="form-select">
                <option value="">الكل</option>
                <option value="دخل" <?= $filterType == 'دخل' ? 'selected' : '' ?>>دخل (إيداع/تحويل)</option>
                <option value="خرج" <?= $filterType == 'خرج' ? 'selected' : '' ?>>خرج (سحب/سلفة)</option>
            </select>
        </div>
        <div class="col-12 d-flex justify-content-center pt-2">
            <button class="btn btn-primary me-2"><i class="fas fa-search me-2"></i>بحث</button>
            <a href="cashbox_index.php" class="btn btn-secondary me-2"><i class="fas fa-eraser me-2"></i>إعادة تعيين</a>
            <a href="cashbox_list.php" class="btn btn-dark"><i class="fas fa-list me-2"></i>السجل الكلي (المبيعات والمصروفات)</a>
        </div>
    </form>
    
    <?php if ($can_add): ?>
    <div class="row mb-4">
        <div class="col-12 text-center">
            <a href="cashbox_add.php" class="btn btn-success"><i class="fas fa-plus me-2"></i>إضافة عملية صندوق جديدة</a>
        </div>
    </div>
    <?php endif; ?>

    <div class="card shadow-lg">
        <div class="card-body table-responsive">
            <p class="text-muted text-center">عرض **<?= count($rows) ?>** من **<?= $total_rows_filtered ?>** حركة (الصفحة <?= $page ?>)</p>

            <?php if ($rows): ?>
                <table class="table table-bordered table-hover text-center align-middle">
                    <thead class="table-dark">
                        <tr>
                            <th>#</th>
                            <th>التاريخ</th>
                            <th>**نوع الحركة**</th>
                            <th>التصنيف</th>
                            <th>المبلغ</th>
                            <th>الموظف/المرتبط</th>
                            <th>أُدخل بواسطة</th>
                            <th>الملاحظات</th>
                            <?php if ($can_edit || $can_delete): ?>
                            <th>الإجراءات</th>
                            <?php endif; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($rows as $i => $row): ?>
                            <?php
                            $type_badge = ($row['type'] == 'دخل') ? 'bg-success' : 'bg-danger';
                            $row_number = $offset + $i + 1;
                            ?>
                            <tr>
                                <td><?= $row_number ?></td>
                                <td><?= htmlspecialchars($row['date']) ?></td>
                                <td><span class="badge <?= $type_badge ?>"><?= htmlspecialchars($row['type']) ?></span></td>
                                <td><?= htmlspecialchars($row['operation_type']) ?></td>
                                <td class="fw-bold"><?= number_format($row['amount'], 2) ?> د.ع</td>
                                <td><?= htmlspecialchars($row['employee_name'] ?? 'غير محدد') ?></td>
                                <td><?= htmlspecialchars($row['created_by_name'] ?? 'غير محدد') ?></td>
                                <td><?= htmlspecialchars($row['description']) ?></td>
                                
                                <?php if ($can_edit || $can_delete): ?>
                                <td class="text-nowrap">
                                    <?php if ($can_edit): ?>
                                    <a href="cashbox_edit.php?id=<?= $row['id'] ?>" class="btn btn-sm btn-info text-white me-1" title="تعديل">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <?php endif; ?>
                                    
                                    <?php if ($can_delete): ?>
                                    <button class="btn btn-sm btn-danger delete-btn" 
                                            data-id="<?= $row['id'] ?>" 
                                            data-bs-toggle="modal" 
                                            data-bs-target="#deleteModal" 
                                            title="حذف">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                    <?php endif; ?>
                                </td>
                                <?php endif; ?>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <div class="alert alert-info text-center">لا توجد حركات صندوق رئيسي مسجلة ضمن الفلاتر المحددة.</div>
            <?php endif; ?>

            <?php if ($total_pages > 1): ?>
                <nav aria-label="Page navigation">
                    <ul class="pagination justify-content-center">
                        <?php 
                        // بناء سلسلة الاستعلام للحفاظ على الفلاتر
                        $query_params = $_GET;
                        unset($query_params['p']);
                        $query_string = http_build_query($query_params);

                        $prev_page = max(1, $page - 1);
                        ?>
                        <li class="page-item <?= ($page <= 1) ? 'disabled' : '' ?>">
                            <a class="page-link" href="?p=<?= $prev_page ?>&<?= $query_string ?>" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>

                        <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                            <li class="page-item <?= ($i == $page) ? 'active' : '' ?>">
                                <a class="page-link" href="?p=<?= $i ?>&<?= $query_string ?>"><?= $i ?></a>
                            </li>
                        <?php endfor; ?>

                        <?php 
                        $next_page = min($total_pages, $page + 1);
                        ?>
                        <li class="page-item <?= ($page >= $total_pages) ? 'disabled' : '' ?>">
                            <a class="page-link" href="?p=<?= $next_page ?>&<?= $query_string ?>" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                    </ul>
                </nav>
            <?php endif; ?>
        </div>
    </div>
</div>

<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true" dir="rtl">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header bg-danger text-white">
        <h5 class="modal-title" id="deleteModalLabel">تأكيد الحذف</h5>
        <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        هل أنت متأكد من أنك تريد حذف هذه العملية من سجل الصندوق؟
        <br><strong class="text-danger">هذا الإجراء سيؤثر على الرصيد الكلي.</strong>
      </div>
      <div class="modal-footer justify-content-start">
        <form method="POST" action="cashbox_delete.php" id="deleteForm">
            <input type="hidden" name="id" id="delete_id">
            <input type="hidden" name="source" value="Cashbox">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">إلغاء</button>
            <button type="submit" class="btn btn-danger">تأكيد الحذف</button>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const deleteButtons = document.querySelectorAll('.delete-btn');
    const deleteIdInput = document.getElementById('delete_id');
    const deleteForm = document.getElementById('deleteForm');

    deleteButtons.forEach(button => {
        button.addEventListener('click', function() {
            const rowId = this.getAttribute('data-id');
            deleteIdInput.value = rowId;
            // توجيه الفورم إلى cashbox_delete.php
            deleteForm.action = 'cashbox_delete.php'; 
        });
    });
});
</script>

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