<?php
require_once 'db/config.php';
require_once 'includes/header.php';
require_once 'includes/accounting_functions.php';

// Check permission
$user_id = $_SESSION['user_id'];
$stmt = db()->prepare("SELECT * FROM user_permissions WHERE user_id = ? AND page = 'accounting' AND can_view = 1");
$stmt->execute([$user_id]);
if (!$stmt->fetch()) {
    echo "<div class='container mt-4' dir='rtl'>لا تملك صلاحية الوصول لهذه الصفحة.</div>";
    require_once 'includes/footer.php';
    exit;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_entry'])) {
    $date = $_POST["date"] ?? "";
    $description = $_POST["description"] ?? "";
    $reference = $_POST["reference"] ?? "";
    $entries = [
        ["account" => $_POST["debit_account"] ?? "", "debit" => (float)($_POST["amount"] ?? 0), "credit" => 0],
        ["account" => $_POST["credit_account"] ?? "", "debit" => 0, "credit" => (float)($_POST["amount"] ?? 0)]
    ];
    
    if (add_journal_entry($date, $description, $reference, $entries)) {
        $message = "تم إضافة القيد بنجاح.";
    } else {
        $error = "حدث خطأ أثناء إضافة القيد.";
    }
}

// Pagination and Filtering setup
$page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;
$search = $_GET['search'] ?? '';
$date_from = $_GET['date_from'] ?? '';
$date_to = $_GET['date_to'] ?? '';

// Fetch ledger data with filters
$ledger_all = get_full_ledger_filtered($search, $date_from, $date_to);
$total_items = count($ledger_all);
$total_pages = ceil($total_items / $limit);
$ledger = array_slice($ledger_all, $offset, $limit);
?>

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<style>
    .table td, .table th { padding: 0.3rem 0.5rem; }
    .action-icon { cursor: pointer; text-decoration: none; }
    .action-icon:hover { opacity: 0.7; }
</style>

<div class="container mt-4" dir="rtl">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="text-right">المحاسبة (Accounting)</h2>
        <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#journalModal">
            <i class="fas fa-plus"></i> إضافة قيد جديد
        </button>
    </div>
    
    <?php if (isset($message)) echo "<div class='alert alert-success'>$message</div>"; ?>
    <?php if (isset($error)) echo "<div class='alert alert-danger'>$error</div>"; ?>

    <!-- Filter Form -->
    <div class="card mb-4 shadow-sm">
        <div class="card-body py-2">
            <form method="GET" class="row g-2 align-items-center">
                <div class="col-md-5">
                    <input type="text" name="search" class="form-control form-control-sm" placeholder="بحث..." value="<?= htmlspecialchars($search) ?>">
                </div>
                <div class="col-md-2">
                    <input type="date" name="date_from" class="form-control form-control-sm" value="<?= htmlspecialchars($date_from) ?>">
                </div>
                <div class="col-md-2">
                    <input type="date" name="date_to" class="form-control form-control-sm" value="<?= htmlspecialchars($date_to) ?>">
                </div>
                <div class="col-md-3 text-end">
                    <button type="submit" class="btn btn-sm btn-secondary"><i class="fas fa-filter"></i> تصفية</button>
                    <a href="accounting.php" class="btn btn-sm btn-outline-secondary"><i class="fas fa-sync"></i></a>
                </div>
            </form>
        </div>
    </div>
    
    <!-- Journal Modal -->
    <div class="modal fade" id="journalModal" tabindex="-1" aria-labelledby="journalModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <form method="POST">
                    <div class="modal-header">
                        <h5 class="modal-title" id="journalModalLabel">إضافة قيد محاسبي</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <input type="hidden" name="add_entry" value="1">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label>التاريخ</label>
                                <input type="date" name="date" class="form-control" required value="<?= date('Y-m-d') ?>">
                            </div>
                            <div class="col-md-6 mb-3">
                                <label>المرجع</label>
                                <input type="text" name="reference" class="form-control">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label>الوصف</label>
                            <input type="text" name="description" class="form-control" required>
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label>حساب المدين</label>
                                <select name="debit_account" class="form-select accountSelect" required style="width: 100%;">
                                    <?php foreach (get_all_accounts() as $acc): ?>
                                    <option value="<?= htmlspecialchars($acc['name']) ?>"><?= htmlspecialchars($acc['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label>حساب الدائن</label>
                                <select name="credit_account" class="form-select accountSelect" required style="width: 100%;">
                                    <?php foreach (get_all_accounts() as $acc): ?>
                                    <option value="<?= htmlspecialchars($acc['name']) ?>"><?= htmlspecialchars($acc['name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-4 mb-3">
                                <label>المبلغ</label>
                                <input type="number" step="0.01" name="amount" class="form-control" required min="0.01">
                            </div>
                        </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>
    
    <div class="row">
        <div class="col-md-12">
            <h3 class="text-right">دفتر الأستاذ (General Ledger)</h3>
            <div class="table-responsive">
                <table class="table table-hover table-bordered text-right align-middle table-sm">
                    <thead class="table-light"><tr><th>التاريخ</th><th>الوصف</th><th>المرجع</th><th>الحساب</th><th>مدين</th><th>دائن</th><th>الإجراءات</th></tr></thead>
                    <tbody>
                        <?php foreach ($ledger as $row): ?>
                        <tr>
                            <td><?= htmlspecialchars($row['date']) ?></td>
                            <td><?= htmlspecialchars($row['description']) ?></td>
                            <td><?= htmlspecialchars($row['reference']) ?></td>
                            <td><?= htmlspecialchars($row['account_name']) ?></td>
                            <td><?= number_format($row['debit'], 2) ?></td>
                            <td><?= number_format($row['credit'], 2) ?></td>
                            <td>
                                <a href="#" class="action-icon text-warning me-2" title="تعديل" onclick="alert('تعديل القيد <?= $row['id'] ?>')"><i class="fas fa-edit"></i></a>
                                <a href="#" class="action-icon text-danger" title="حذف" onclick="if(confirm('هل أنت متأكد؟')) alert('حذف القيد <?= $row['id'] ?>')"><i class="fas fa-trash"></i></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            
            <nav>
                <ul class="pagination pagination-sm justify-content-center">
                    <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                        <a class="page-link" href="?p=<?= $i ?>&search=<?= urlencode($search) ?>&date_from=<?= urlencode($date_from) ?>&date_to=<?= urlencode($date_to) ?>"><?= $i ?></a>
                    </li>
                    <?php endfor; ?>
                </ul>
            </nav>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    $('.accountSelect').select2({
        theme: 'bootstrap-5',
        dir: 'rtl',
        dropdownParent: $('#journalModal')
    });
});
</script>

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