<?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;
}

$message = null;
$messageType = 'success';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['add_account'])) {
        $name = $_POST['name'];
        $type = $_POST['type']; 
        $stmt = db()->prepare("INSERT INTO accounting_accounts (name, type) VALUES (?, ?)");
        if($stmt->execute([$name, $type])) {
            $message = "تم إضافة الحساب بنجاح.";
        }
    } elseif (isset($_POST['delete_account'])) {
        $id = $_POST['id'];
        $stmt = db()->prepare("DELETE FROM accounting_accounts WHERE id = ?");
        if($stmt->execute([$id])) {
            $message = "تم حذف الحساب.";
        }
    } elseif (isset($_POST['edit_account'])) {
        $id = $_POST['id'];
        $name = $_POST['name'];
        $type = $_POST['type'];
        $stmt = db()->prepare("UPDATE accounting_accounts SET name = ?, type = ? WHERE id = ?");
        if($stmt->execute([$name, $type, $id])) {
            $message = "تم تحديث الحساب بنجاح.";
        }
    }
}

// Pagination
$page = isset($_GET['p']) ? (int)$_GET['p'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;

$totalAccounts = db()->query("SELECT COUNT(*) FROM accounting_accounts")->fetchColumn();
$totalPages = ceil($totalAccounts / $limit);

$accounts = db()->prepare("SELECT * FROM accounting_accounts ORDER BY type, name LIMIT ? OFFSET ?");
$accounts->bindValue(1, $limit, PDO::PARAM_INT);
$accounts->bindValue(2, $offset, PDO::PARAM_INT);
$accounts->execute();
$accounts = $accounts->fetchAll(PDO::FETCH_ASSOC);

// Map English types to Arabic
$typeMap = [
    'Assets' => 'أصول',
    'Liabilities' => 'خصوم',
    'Equity' => 'حقوق ملكية',
    'Revenue' => 'إيرادات',
    'Expenses' => 'مصروفات',
    'أصول' => 'أصول',
    'خصوم' => 'خصوم',
    'حقوق ملكية' => 'حقوق ملكية',
    'إيرادات' => 'إيرادات',
    'مصروفات' => 'مصروفات'
];
?>

<!-- SweetAlert2 -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<style>
    /* Reduce row height for a more compact table */
    .table-compact td, .table-compact th {
        padding: 0.4rem 0.6rem;
        vertical-align: middle;
        font-size: 0.95rem;
    }
    .table-compact .btn-sm {
        padding: 0.2rem 0.4rem;
        font-size: 0.8rem;
    }
</style>

<div class="container mt-4" dir="rtl">
    <h2 class="text-right mb-4">دليل الحسابات</h2>
    
    <div class="card mb-4 shadow-sm border-0">
        <div class="card-header bg-primary text-white">إضافة/تعديل حساب</div>
        <div class="card-body bg-light">
            <form method="POST" id="accountForm">
                <input type="hidden" name="add_account" value="1" id="formAction">
                <input type="hidden" name="id" id="editId">
                <div class="row">
                    <div class="col-md-5 mb-2">
                        <label class="font-weight-bold">اسم الحساب</label>
                        <input type="text" name="name" class="form-control" id="editName" required>
                    </div>
                    <div class="col-md-5 mb-2">
                        <label class="font-weight-bold">نوع الحساب</label>
                        <select name="type" class="form-control" id="editType" required>
                            <option value="أصول">أصول</option>
                            <option value="خصوم">خصوم</option>
                            <option value="حقوق ملكية">حقوق ملكية</option>
                            <option value="إيرادات">إيرادات</option>
                            <option value="مصروفات">مصروفات</option>
                        </select>
                    </div>
                    <div class="col-md-2 d-flex align-items-end mb-2">
                        <button type="submit" class="btn btn-primary w-100 shadow-sm" id="formButton">
                            <i class="fas fa-plus"></i> إضافة
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    
    <div class="card shadow-sm border-0">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-bordered table-striped table-hover table-compact text-right mb-0">
                    <thead class="thead-dark">
                        <tr>
                            <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 style="width: 120px; text-align: center;">إجراءات</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($accounts as $account): ?>
                        <tr>
                            <td><?= htmlspecialchars($account['name']) ?></td>
                            <td>
                                <span class="badge badge-info px-2 py-1" style="color: black;">
                                    <?= htmlspecialchars($typeMap[$account['type']] ?? $account['type']) ?>
                                </span>
                            </td>
                            <td><small class="text-muted"><i class="fas fa-user text-primary opacity-50 me-1"></i><?= htmlspecialchars(getAuditUserName($account['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($account['updated_by'] ?? null)) ?></small></td>
                            <td class="text-center">
                                <button class="btn btn-warning text-white btn-sm shadow-sm mx-1" onclick="editAccount(<?= $account['id'] ?>, '<?= htmlspecialchars($account['name'], ENT_QUOTES) ?>', '<?= htmlspecialchars($account['type'], ENT_QUOTES) ?>')" title="تعديل">
                                    <i class="fas fa-pencil-alt"></i>
                                </button>
                                <form method="POST" style="display:inline;" class="delete-form">
                                    <input type="hidden" name="delete_account" value="1">
                                    <input type="hidden" name="id" value="<?= $account['id'] ?>">
                                    <button type="button" class="btn btn-danger btn-sm shadow-sm mx-1" onclick="confirmDelete(this)" title="حذف">
                                        <i class="fas fa-trash-alt"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($accounts)): ?>
                        <tr>
                            <td colspan="3" class="text-center py-3 text-muted">لا توجد حسابات مضافة بعد.</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <?php if ($totalPages > 1): ?>
    <nav class="mt-4">
        <ul class="pagination justify-content-center">
            <?php for ($i = 1; $i <= $totalPages; $i++): ?>
                <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                    <a class="page-link" href="?p=<?= $i ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>
        </ul>
    </nav>
    <?php endif; ?>
</div>

<script>
// SweetAlert Success Message from PHP
<?php if ($message): ?>
document.addEventListener('DOMContentLoaded', function() {
    Swal.fire({
        icon: 'success',
        title: 'نجاح!',
        text: '<?= htmlspecialchars($message) ?>',
        confirmButtonText: 'حسناً',
        confirmButtonColor: '#28a745',
        timer: 3000,
        timerProgressBar: true
    });
});
<?php endif; ?>

function editAccount(id, name, type) {
    document.getElementById('formAction').name = 'edit_account';
    document.getElementById('editId').value = id;
    document.getElementById('editName').value = name;
    document.getElementById('editType').value = type;
    
    const formBtn = document.getElementById('formButton');
    formBtn.innerHTML = '<i class="fas fa-save"></i> حفظ التعديلات';
    formBtn.classList.remove('btn-primary');
    formBtn.classList.add('btn-success');
    
    // Animate scroll to form
    window.scrollTo({top: 0, behavior: 'smooth'});
    
    // Highlight form briefly to show it's in edit mode
    const cardBody = document.querySelector('.card-body');
    cardBody.style.transition = 'background-color 0.5s';
    cardBody.style.backgroundColor = '#fff3cd'; // warning light
    setTimeout(() => {
        cardBody.style.backgroundColor = '';
    }, 1000);
}

function confirmDelete(button) {
    Swal.fire({
        title: 'هل أنت متأكد؟',
        text: "لن تتمكن من استعادة هذا الحساب لاحقاً!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        cancelButtonColor: '#6c757d',
        confirmButtonText: '<i class="fas fa-trash-alt"></i> نعم، احذفه!',
        cancelButtonText: 'إلغاء',
        reverseButtons: true
    }).then((result) => {
        if (result.isConfirmed) {
            button.closest('.delete-form').submit();
        }
    });
}
</script>

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