<?php
// filename: expense_categories.php
session_start();
include 'layouts/dbconn.php';
include 'layouts/session.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'FINANCE_MANAGER'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.php');
    exit();
}

$user_id = $_SESSION['user_id'];
$message = '';
$error = '';

// Handle CRUD
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $account_id = (int)$_POST['account_id'];
    $account_code = trim($_POST['account_code'] ?? '');
    $account_name = trim($_POST['account_name'] ?? '');
    $account_category = trim($_POST['account_category'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $parent_id = (int)$_POST['parent_id'] ?? null;
    $is_header = (int)$_POST['is_header'] ?? 0;
    
    if ($action === 'add' || $action === 'edit') {
        if (empty($account_name) || empty($account_code)) {
            $error = 'Name and code required.';
        } else {
            if ($action === 'add') {
                $cat_sql = "INSERT INTO chart_of_accounts (account_code, account_name, account_type, account_category, parent_account_id, is_header, description, is_active, created_at) 
                            VALUES (?, ?, 'EXPENSE', ?, ?, ?, ?, 1, CURRENT_TIMESTAMP)";
                $cat_stmt = $conn->prepare($cat_sql);
                $cat_stmt->bind_param('sssis', $account_code, $account_name, $account_category, $parent_id, $description, $is_header);
            } else {
                $cat_sql = "UPDATE chart_of_accounts SET account_code = ?, account_name = ?, account_category = ?, parent_account_id = ?, is_header = ?, description = ? WHERE account_id = ?";
                $cat_stmt = $conn->prepare($cat_sql);
                $cat_stmt->bind_param('sssisii', $account_code, $account_name, $account_category, $parent_id, $is_header, $description, $account_id);
            }
            if ($cat_stmt->execute()) {
                $message = 'Category ' . ($action === 'add' ? 'added' : 'updated') . ' successfully!';
                // Log activity
                $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values) VALUES (?, ?, 'EXPENSE_CATEGORY', ?, 'CHART_OF_ACCOUNTS', ?)";
                $log_values = json_encode(['name' => $account_name, 'action' => $action]);
                $log_stmt = $conn->prepare($log_sql);
                $log_stmt->bind_param('sii s', $action, $conn->insert_id ?: $account_id, $log_values, $user_id);
                $log_stmt->execute();
            } else {
                $error = 'Failed to save category.';
            }
        }
    } elseif ($action === 'delete') {
        $del_sql = "DELETE FROM chart_of_accounts WHERE account_id = ? AND account_type = 'EXPENSE'";
        $del_stmt = $conn->prepare($del_sql);
        $del_stmt->bind_param('i', $account_id);
        if ($del_stmt->execute()) {
            $message = 'Category deleted successfully!';
            // Log
            // Similar log
        } else {
            $error = 'Failed to delete category (may have sub-accounts).';
        }
    }
}

// Fetch expense categories (chart_of_accounts where account_type = 'EXPENSE')
$cat_sql = "SELECT ca.*, pa.account_name as parent_name FROM chart_of_accounts ca 
            LEFT JOIN chart_of_accounts pa ON ca.parent_account_id = pa.account_id 
            WHERE ca.account_type = 'EXPENSE' AND ca.is_active = 1 ORDER BY ca.account_category, ca.account_name";
$cat_result = $conn->query($cat_sql);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Expense Categories')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">Expense Categories</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="dashboard.php">Dashboard</a></li>
                                        <li class="breadcrumb-item active">Categories</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="row">
                        <div class="col-lg-8 mx-auto">
                            <div class="card expense-card">
                                <div class="card-header expense-header">
                                    <h5 class="mb-0 text-white"><i class="ri-menu-line me-2"></i>Manage Categories</h5>
                                </div>
                                <div class="card-body">
                                    <?php if ($message): ?>
                                    <div class="alert alert-success"><?php echo htmlspecialchars($message); ?></div>
                                    <?php endif; ?>
                                    
                                    <?php if ($error): ?>
                                    <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
                                    <?php endif; ?>
                                    
                                    <!-- Add/Edit Form -->
                                    <form method="POST" id="categoryForm">
                                        <input type="hidden" name="action" value="add">
                                        <input type="hidden" name="account_id" value="0">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Code</label>
                                                <input type="text" class="form-control" name="account_code" placeholder="e.g., EXP-001">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Name <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" name="account_name" placeholder="e.g., Office Supplies" required>
                                            </div>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Category</label>
                                                <input type="text" class="form-control" name="account_category" placeholder="e.g., Operational">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">Parent Account</label>
                                                <select class="form-select" name="parent_id">
                                                    <option value="">None</option>
                                                    <!-- Loop parents -->
                                                    <?php 
                                                    $parent_sql = "SELECT account_id, account_name FROM chart_of_accounts WHERE account_type = 'EXPENSE' AND is_header = 1 ORDER BY account_name";
                                                    $parent_result = $conn->query($parent_sql);
                                                    while ($parent = $parent_result->fetch_assoc()): 
                                                    ?>
                                                    <option value="<?php echo $parent['account_id']; ?>"><?php echo htmlspecialchars($parent['account_name']); ?></option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Description</label>
                                            <textarea class="form-control" name="description" rows="2"></textarea>
                                        </div>
                                        <div class="mb-3">
                                            <div class="form-check">
                                                <input class="form-check-input" type="checkbox" name="is_header" value="1" id="is_header">
                                                <label class="form-check-label" for="is_header">Header Account (no postings)</label>
                                            </div>
                                        </div>
                                        <button type="submit" class="btn btn-primary">
                                            <i class="ri-save-line me-1"></i>Save Category
                                        </button>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Categories List -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <div class="card expense-card">
                                <div class="card-header expense-header">
                                    <h5 class="mb-0 text-white"><i class="ri-list-ordered me-2"></i>Expense Categories List</h5>
                                </div>
                                <div class="card-body p-0">
                                    <div class="table-responsive">
                                        <table class="table table-sm mb-0">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>Code</th>
                                                    <th>Name</th>
                                                    <th>Category</th>
                                                    <th>Parent</th>
                                                    <th>Type</th>
                                                    <th>Actions</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($cat = $cat_result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo htmlspecialchars($cat['account_code']); ?></td>
                                                    <td><?php echo htmlspecialchars($cat['account_name']); ?></td>
                                                    <td><?php echo htmlspecialchars($cat['account_category'] ?? 'N/A'); ?></td>
                                                    <td><?php echo htmlspecialchars($cat['parent_name'] ?? 'N/A'); ?></td>
                                                    <td><?php echo $cat['is_header'] ? 'Header' : 'Posting'; ?></td>
                                                    <td>
                                                        <button class="btn btn-sm btn-outline-primary" onclick="editCategory(<?php echo $cat['account_id']; ?>)">
                                                            <i class="ri-edit-line"></i> Edit
                                                        </button>
                                                        <button class="btn btn-sm btn-outline-danger" onclick="deleteCategory(<?php echo $cat['account_id']; ?>)">
                                                            <i class="ri-delete-bin-line"></i> Delete
                                                        </button>
                                                    </td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="assets/js/app.js"></script>
    
    <script>
    function editCategory(id) {
        // AJAX to fetch and populate form
        $.get('ajax/get_category.php', { id: id }, function(data) {
            // Parse JSON, set form fields
            const cat = JSON.parse(data);
            $('input[name="account_id"]').val(cat.account_id);
            $('input[name="account_code"]').val(cat.account_code);
            $('input[name="account_name"]').val(cat.account_name);
            // etc.
            $('input[name="action"]').val('edit');
        });
    }
    
    function deleteCategory(id) {
        Swal.fire({
            title: 'Delete Category?',
            icon: 'warning',
            showCancelButton: true
        }).then((result) => {
            if (result.isConfirmed) {
                $.post('', { action: 'delete', account_id: id }, function(response) {
                    if (response.success) {
                        location.reload();
                    } else {
                        Swal.fire('Error', response.message, 'error');
                    }
                }, 'json');
            }
        });
    }
    </script>
</body>
</html>