<?php
require_once __DIR__ . '/includes/header.php';

if (!canView('expense_settings')) {
    redirect('index.php');
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!canEdit('expense_settings')) redirect('expense_categories.php');
    
    $action = $_POST['action'] ?? '';
    $id = $_POST['id'] ?? 0;
    $name = trim($_POST['name'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $account_id = !empty($_POST['account_id']) ? $_POST['account_id'] : null;
    
    if ($name) {
        try {
            $db = db();
            if ($action === 'add') {
                $stmt = $db->prepare("INSERT INTO expense_categories (name, description, account_id) VALUES (?, ?, ?)");
                $stmt->execute([$name, $description, $account_id]);
                $_SESSION['success'] = 'تم إضافة التصنيف بنجاح';
            } elseif ($action === 'edit' && $id) {
                $stmt = $db->prepare("UPDATE expense_categories SET name = ?, description = ?, account_id = ? WHERE id = ?");
                $stmt->execute([$name, $description, $account_id, $id]);
                $_SESSION['success'] = 'تم تحديث التصنيف بنجاح';
            }
            redirect('expense_categories.php');
        } catch (PDOException $e) {
            $error = 'حدث خطأ: ' . $e->getMessage();
        }
    } else {
        $error = 'اسم التصنيف مطلوب';
    }
}

if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['id'])) {
    if (!canDelete('expense_settings')) redirect('expense_categories.php');
    $id = $_GET['id'];
    try {
        $db = db();
        $stmt = $db->prepare("DELETE FROM expense_categories WHERE id = ?");
        $stmt->execute([$id]);
        $_SESSION['success'] = 'تم حذف التصنيف بنجاح';
    } catch (PDOException $e) {
        if ($e->getCode() == 23000) {
            $_SESSION['error'] = 'لا يمكن حذف هذا التصنيف لأنه مرتبط بمصروفات مسجلة';
        } else {
            $_SESSION['error'] = 'حدث خطأ: ' . $e->getMessage();
        }
    }
    redirect('expense_categories.php');
}

$categories = db()->query("SELECT c.*, a.name as account_name FROM expense_categories c LEFT JOIN accounting_accounts a ON c.account_id = a.id ORDER BY c.name")->fetchAll(PDO::FETCH_ASSOC);
$accounts = db()->query("SELECT * FROM accounting_accounts ORDER BY type, name")->fetchAll(PDO::FETCH_ASSOC);

if (isset($_SESSION['success'])) {
    $success = $_SESSION['success'];
    unset($_SESSION['success']);
}
if (isset($_SESSION['error'])) {
    $error = $_SESSION['error'];
    unset($_SESSION['error']);
}
?>

<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
    <h1 class="h2">إعدادات تصنيفات المصروفات</h1>
    <?php if (canAdd('expense_settings')): ?>
    <button type="button" class="btn btn-primary shadow-sm" onclick="openModal('add')">
        <i class="fas fa-plus"></i> إضافة تصنيف جديد
    </button>
    <?php endif; ?>
</div>

<?php if ($success): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?= $success ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<?php if ($error): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <?= $error ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
<?php endif; ?>

<div class="card shadow-sm border-0">
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="bg-light">
                    <tr>
                        <th class="ps-4">اسم التصنيف</th>
                        <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 class="text-center">الإجراءات</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($categories as $cat): ?>
                        <tr>
                            <td class="ps-4 fw-bold"><?= htmlspecialchars($cat['name']) ?></td>
                            <td>
                                <?php if($cat['account_name']): ?>
                                    <span class="badge bg-info text-dark"><?= htmlspecialchars($cat['account_name']) ?></span>
                                <?php else: ?>
                                    <span class="text-muted text-small">غير مرتبط</span>
                                <?php endif; ?>
                            </td>
                            <td><?= htmlspecialchars($cat['description']) ?></td>
                            <td><small class="text-muted"><i class="fas fa-user text-primary opacity-50 me-1"></i><?= htmlspecialchars(getAuditUserName($cat['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($cat['updated_by'] ?? null)) ?></small></td>
                            <td class="text-center">
                                <?php if (canEdit('expense_settings')): ?>
                                <button class="btn btn-sm btn-outline-primary" onclick='openModal("edit", <?= json_encode($cat, JSON_HEX_APOS | JSON_HEX_QUOT) ?>)'>
                                    <i class="fas fa-edit"></i>
                                </button>
                                <?php endif; ?>
                                <?php if (canDelete('expense_settings')): ?>
                                <a href="javascript:void(0)" onclick="confirmDelete(<?= $cat['id'] ?>)" class="btn btn-sm btn-outline-danger">
                                    <i class="fas fa-trash"></i>
                                </a>
                                <?php endif; ?>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="categoryModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="modalTitle">تصنيف جديد</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" id="modalAction" value="add">
                    <input type="hidden" name="id" id="modalId" value="0">
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">اسم التصنيف</label>
                        <input type="text" name="name" id="modalName" class="form-control" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label fw-bold">الحساب المحاسبي (للمزامنة التلقائية)</label>
                        <select name="account_id" id="modalAccountId" class="form-select">
                            <option value="">-- اختر الحساب --</option>
                            <?php foreach($accounts as $acc): ?>
                                <option value="<?= $acc['id'] ?>">
                                    <?= htmlspecialchars($acc['name']) ?> (<?= $acc['type'] ?>)
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <div class="form-text">عند تسجيل مصروف بهذا التصنيف، سيتم إنشاء قيد محاسبي تلقائياً على هذا الحساب.</div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">الوصف</label>
                        <textarea name="description" id="modalDescription" class="form-control" rows="3"></textarea>
                    </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>

<script>
let categoryModal;

function openModal(action, data = null) {
    if (!categoryModal) {
        categoryModal = new bootstrap.Modal(document.getElementById('categoryModal'));
    }
    
    document.getElementById('modalAction').value = action;
    const title = document.getElementById('modalTitle');
    
    if (action === 'add') {
        title.textContent = 'تصنيف جديد';
        document.getElementById('modalId').value = 0;
        document.getElementById('modalName').value = '';
        document.getElementById('modalDescription').value = '';
        document.getElementById('modalAccountId').value = '';
    } else {
        title.textContent = 'تعديل التصنيف';
        document.getElementById('modalId').value = data.id;
        document.getElementById('modalName').value = data.name;
        document.getElementById('modalDescription').value = data.description;
        document.getElementById('modalAccountId').value = data.account_id || '';
    }
    
    categoryModal.show();
}

function confirmDelete(id) {
    if (confirm('هل أنت متأكد من الحذف؟')) {
        window.location.href = 'expense_categories.php?action=delete&id=' + id;
    }
}
</script>

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