<?php
session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Get user details for permission checks
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
}

// Function to generate a new request number
function generateRequestNumber($conn) {
    $year = date('y');
    $month = date('m');
    
    // Get the last request number
    $sql = "SELECT request_number FROM fund_requests 
            WHERE request_number LIKE 'FR-$year$month-%' 
            ORDER BY request_id DESC LIMIT 1";
    $result = $conn->query($sql);
    
    if ($result && $result->num_rows > 0) {
        $row = $result->fetch_assoc();
        $last_number = $row['request_number'];
        $number = intval(substr($last_number, -4)) + 1;
    } else {
        $number = 1;
    }
    
    // Format with leading zeros (4 digits)
    $formatted_number = sprintf("%04d", $number);
    return "FR-$year$month-$formatted_number";
}

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Begin transaction
    $conn->begin_transaction();
    
    try {
        // Get form data
        $expense_type = $_POST['expense_type'];
        $file_number = null;
        $category_id = null;
        
        if ($expense_type === 'file') {
            $file_number = $_POST['file_number'];
            if (empty($file_number)) {
                throw new Exception("Please select a file number for the file-based expense.");
            }
            
            // For file-based expenses, get category from cost_description field
            if (isset($_POST['cost_reference_id']) && !empty($_POST['cost_reference_id'])) {
                $category_id = $_POST['cost_reference_id'];
            } else {
                // Extract category_id from the description field (which contains the cost code)
                $cost_description = $_POST['description'];
                if (!empty($cost_description)) {
                    // Extract the code part before the hyphen
                    $parts = explode(' - ', $cost_description);
                    if (count($parts) > 0) {
                        // Use the code as category_id
                        $category_id = $parts[0];
                    }
                }
                
                // If still null, set a default category
                if (empty($category_id)) {
                    // Get the first available cost reference
                    $default_cat_sql = "SELECT id FROM cost_reference LIMIT 1";
                    $default_cat_result = $conn->query($default_cat_sql);
                    if ($default_cat_result && $default_cat_result->num_rows > 0) {
                        $default_cat_row = $default_cat_result->fetch_assoc();
                        $category_id = $default_cat_row['id'];
                    } else {
                        $category_id = 1; // Fallback default if no cost references exist
                    }
                }
            }
        } else {
            // For office-based expenses, get category from the category dropdown
            if (isset($_POST['category_id']) && !empty($_POST['category_id'])) {
                $category_id = $_POST['category_id'];
            } else {
                throw new Exception("Please select an expense category.");
            }
        }
        
        $amount = $_POST['amount'];
        if (!is_numeric($amount) || $amount <= 0) {
            throw new Exception("Please enter a valid amount greater than zero.");
        }
        
        $currency = $_POST['currency'];
        $description = $_POST['description'];
        $remarks = $_POST['remarks'] ?? '';
        
        // Generate request number
        $request_number = generateRequestNumber($conn);
        
        // Set request date
        $request_date = date('Y-m-d H:i:s');
        
        // Insert fund request
        $sql = "INSERT INTO fund_requests (
                    request_number, category_id, file_number, amount, currency, 
                    description, status, request_date, requested_by, remarks
                ) VALUES (?, ?, ?, ?, ?, ?, 'Pending', ?, ?, ?)";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param(
            "sisdsssss", 
            $request_number, $category_id, $file_number, $amount, $currency, 
            $description, $request_date, $user_id, $remarks
        );
        
        if (!$stmt->execute()) {
            throw new Exception("Error inserting fund request: " . $stmt->error);
        }
        
        $request_id = $conn->insert_id;
        
        // Handle file attachments
        if (isset($_FILES['attachments']) && !empty($_FILES['attachments']['name'][0])) {
            $upload_dir = 'uploads/fund_requests/';
            
            // Create directory if it doesn't exist
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0777, true);
            }
            
            $attachments = [];
            $files = $_FILES['attachments'];
            
            for ($i = 0; $i < count($files['name']); $i++) {
                if ($files['name'][$i] != '') {
                    $file_name = $files['name'][$i];
                    $file_tmp = $files['tmp_name'][$i];
                    $file_size = $files['size'][$i];
                    $file_type = $files['type'][$i];
                    
                    // Create a unique filename
                    $unique_name = time() . '_' . $user_id . '_' . uniqid() . '_' . $file_name;
                    $file_path = $upload_dir . $unique_name;
                    
                    // Move file to upload directory
                    if (move_uploaded_file($file_tmp, $file_path)) {
                        // Insert attachment record
                        $attach_sql = "INSERT INTO fund_request_attachments (
                                        request_id, file_name, file_path, file_type, file_size, uploaded_by
                                      ) VALUES (?, ?, ?, ?, ?, ?)";
                        $attach_stmt = $conn->prepare($attach_sql);
                        $attach_stmt->bind_param("issisi", $request_id, $file_name, $file_path, $file_type, $file_size, $user_id);
                        
                        if (!$attach_stmt->execute()) {
                            throw new Exception("Error saving attachment: " . $attach_stmt->error);
                        }
                        
                        $attach_stmt->close();
                        $attachments[] = $file_path;
                    }
                }
            }
            
            // Update fund request with attachment info
            if (!empty($attachments)) {
                $attachments_json = json_encode($attachments);
                $update_sql = "UPDATE fund_requests SET attachments = ? WHERE request_id = ?";
                $update_stmt = $conn->prepare($update_sql);
                $update_stmt->bind_param("si", $attachments_json, $request_id);
                $update_stmt->execute();
                $update_stmt->close();
            }
        }
        
        // Add to log
        $log_sql = "INSERT INTO fund_request_logs (
                        request_id, action, status_to, amount_after, performed_by, remarks
                    ) VALUES (?, 'Created', 'Pending', ?, ?, 'Fund request created')";
        $log_stmt = $conn->prepare($log_sql);
        $log_stmt->bind_param("idi", $request_id, $amount, $user_id);
        $log_stmt->execute();
        $log_stmt->close();
        
        // Commit transaction
        $conn->commit();
        
        $_SESSION['success_message'] = "Fund request submitted successfully. Request Number: $request_number";
        header('Location: fund_request_list.php');
        exit();
        
    } catch (Exception $e) {
        // Rollback transaction
        $conn->rollback();
        $_SESSION['error_message'] = "Error: " . $e->getMessage();
    }
}

// Get expense categories for office expenses
$categories_sql = "SELECT * FROM expense_ref ORDER BY code";
$categories_result = $conn->query($categories_sql);
$categories = [];

if ($categories_result->num_rows > 0) {
    while ($row = $categories_result->fetch_assoc()) {
        $categories[] = $row;
    }
}

// Get non-operational cost references for file-based expenses
$cost_reference_sql = "SELECT * FROM cost_reference WHERE category = 'Non-Operational' ORDER BY code";
$cost_reference_result = $conn->query($cost_reference_sql);
$cost_references = [];

if ($cost_reference_result->num_rows > 0) {
    while ($row = $cost_reference_result->fetch_assoc()) {
        $cost_references[] = $row;
    }
}

// Get files for dropdown
$files_sql = "SELECT f.file_number, f.consignee_name, c.first_name 
              FROM files f 
              LEFT JOIN customers c ON f.customer = c.customer_id
              ORDER BY f.created_date DESC LIMIT 1000";
$files_result = $conn->query($files_sql);
$files = [];

if ($files_result->num_rows > 0) {
    while ($row = $files_result->fetch_assoc()) {
        $files[] = $row;
    }
}

// Get system name from settings
$sql_settings = "SELECT setting_value FROM settings WHERE setting_key = 'system_name'";
$result_settings = $conn->query($sql_settings);
if ($result_settings && $result_settings->num_rows > 0) {
    $row_settings = $result_settings->fetch_assoc();
    $system_name = $row_settings['setting_value'];
} else {
    $system_name = "Royal Freight Management System";
}
?>

<?php include 'layouts/main.php'; ?>
<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'New Fund Request')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Select2 CSS -->
    <link href="assets/libs/select2/select2.min.css" rel="stylesheet" type="text/css" />
    
    <!-- Dropzone CSS -->
    <link href="assets/libs/dropzone/dropzone.min.css" rel="stylesheet" type="text/css" />
    
    <!-- Sweet Alert css -->
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11.3.0/dist/sweetalert2.min.js"></script>
    
    <style>
        .category-badge {
            font-size: 12px;
            padding: 5px 8px;
            border-radius: 4px;
            margin-left: 10px;
        }
        .select2-container .select2-selection--single {
            height: 38px;
            border: 1px solid #ced4da;
        }
        .select2-container .select2-selection--single .select2-selection__rendered {
            line-height: 36px;
            padding-left: 12px;
        }
        .select2-container .select2-selection--single .select2-selection__arrow {
            height: 34px;
        }
        .required-field::after {
            content: "*";
            color: red;
            margin-left: 4px;
        }
        .dropzone {
            min-height: 150px;
            border: 2px dashed #e9ebec;
            background: #f8f9fa;
            border-radius: 6px;
        }
        .expense-type-card {
            cursor: pointer;
            border: 2px solid #e9ebec;
            transition: all 0.3s ease;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
        }
        .expense-type-card.active {
            border-color: #0ab39c;
            background-color: rgba(10, 179, 156, 0.1);
        }
        .expense-type-card i {
            font-size: 24px;
            color: #405189;
        }
        .expense-type-card.active i {
            color: #0ab39c;
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Fund Management', 'title' => 'New Fund Request')); ?>

                    <?php
                    // Show success message if set
                    if (isset($_SESSION['success_message'])) {
                        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">';
                        echo $_SESSION['success_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['success_message']);
                    }
                    
                    // Show error message if set
                    if (isset($_SESSION['error_message'])) {
                        echo '<div class="alert alert-danger alert-dismissible fade show" role="alert">';
                        echo $_SESSION['error_message'];
                        echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
                        echo '</div>';
                        unset($_SESSION['error_message']);
                    }
                    ?>

                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <h4 class="card-title mb-0">Create New Fund Request</h4>
                                </div>
                                <div class="card-body">
                                    <form action="" method="POST" enctype="multipart/form-data" id="fundRequestForm">
                                        <div class="row mb-4">
                                            <div class="col-md-12">
                                                <label class="form-label required-field">Expense Type</label>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="expense-type-card active" id="office_based_card" onclick="selectExpenseType('office')">
                                                            <div class="d-flex align-items-center">
                                                                <div class="flex-shrink-0">
                                                                    <i class="ri-building-line"></i>
                                                                </div>
                                                                <div class="flex-grow-1 ms-3">
                                                                    <h5 class="mb-1">Office Based</h5>
                                                                    <p class="text-muted mb-0">General office expenses not related to specific files</p>
                                                                    <input type="radio" name="expense_type" id="office_based" value="office" checked class="d-none">
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="expense-type-card" id="file_based_card" onclick="selectExpenseType('file')">
                                                            <div class="d-flex align-items-center">
                                                                <div class="flex-shrink-0">
                                                                    <i class="ri-file-list-3-line"></i>
                                                                </div>
                                                                <div class="flex-grow-1 ms-3">
                                                                    <h5 class="mb-1">File Based</h5>
                                                                    <p class="text-muted mb-0">Expenses related to a specific shipment file</p>
                                                                    <input type="radio" name="expense_type" id="file_based" value="file" class="d-none">
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-6">
                                                <!-- File-based selection section -->
                                                <div class="mb-3" id="file_based_fields" style="display: none;">
                                                    <label for="file_number" class="form-label required-field">Job Number</label>
                                                    <select class="form-control select2" name="file_number" id="file_number">    
                                                        <option value="">Please Select A Job Number</option>
                                                        <?php foreach ($files as $file): ?>
                                                            <option value="<?php echo $file['file_number']; ?>">
                                                                <?php echo $file['file_number'] . ' - ' . htmlspecialchars($file['consignee_name']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <div class="form-text">Select the file/job this expense relates to</div>
                                                </div>

                                                <!-- Office-based selection section -->
                                                <div class="mb-3" id="office_based_fields">
                                                    <label for="category_id" class="form-label required-field">Office Cost Category</label>
                                                    <select class="form-control select2" id="category_id" name="category_id">
                                                        <option value="">Select Expense Category</option>
                                                        <?php foreach ($categories as $category): ?>
                                                            <option value="<?php echo $category['idx']; ?>">
                                                                <?php echo htmlspecialchars($category['description']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <div class="form-text">Select the type of office expense</div>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="amount" class="form-label required-field">Amount</label>
                                                    <input type="number" class="form-control" id="amount" name="amount" required min="0.01" step="0.01">
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="currency" class="form-label required-field">Currency</label>
                                                    <select class="form-control" id="currency" name="currency" required>
                                                        <option value="USD">USD ($)</option>
                                                        <option value="TSH">TSH (Tsh)</option>
                                                    </select>
                                                </div>
                                            </div>
                                            
                                            <div class="col-md-6">
                                                <!-- Description field for Office-based expenses -->
                                                <div class="mb-3" id="office_description_field">
                                                    <label for="description" class="form-label required-field">Description</label>
                                                    <textarea class="form-control" id="description" name="description" rows="3" required></textarea>
                                                    <div class="form-text">Provide a clear description of what this fund is for.</div>
                                                </div>
                                                
                                                <!-- Description dropdown for File-based expenses -->
                                                <div class="mb-3" id="file_description_field" style="display: none;">
                                                    <label for="cost_description" class="form-label required-field">Expense Type</label>
                                                    <select class="form-control select2" id="cost_description" name="description">
                                                        <option value="">Select Cost Type</option>
                                                        <?php foreach ($cost_references as $cost): ?>
                                                            <option value="<?php echo $cost['code'] . ' - ' . $cost['description']; ?>" data-cost-id="<?php echo $cost['id']; ?>">
                                                                <?php echo $cost['code'] . ' - ' . htmlspecialchars($cost['description']); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                    <div class="form-text">Select the type of cost for this shipment file</div>
                                                    <input type="hidden" name="cost_reference_id" id="cost_reference_id">
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="remarks" class="form-label">Additional Remarks</label>
                                                    <textarea class="form-control" id="remarks" name="remarks" rows="2"></textarea>
                                                </div>
                                                
                                                <div class="mb-3">
                                                    <label for="attachments" class="form-label">Attachments</label>
                                                    <input type="file" class="form-control" id="attachments" name="attachments[]" multiple>
                                                    <div class="form-text">You can attach receipts, invoices, or other supporting documents (Max. 5 files).</div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="row mt-3">
                                            <div class="col-12 text-end">
                                                <a href="fund_request_list.php" class="btn btn-secondary me-2">Cancel</a>
                                                <button type="submit" class="btn btn-primary">Submit Request</button>
                                            </div>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/js/app.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

    <!-- Dropzone js -->
    <script src="assets/libs/dropzone/dropzone.min.js"></script>

    
<script>
    $(document).ready(function() {
        // Initialize Select2
       /* $('.select2').select2({
            width: '100%',
            placeholder: function() {
                return $(this).data('placeholder') || "Select an option";
            },
            allowClear: true
        });*/
        
        // File upload validation
        $('#attachments').on('change', function() {
            const files = this.files;
            
            if (files.length > 5) {
                Swal.fire({
                    icon: 'error',
                    title: 'Too Many Files',
                    text: 'You can upload a maximum of 5 files.',
                    confirmButtonColor: '#3085d6'
                });
                $(this).val('');
                return;
            }
            
            // Check file size
            let totalSize = 0;
            for (let i = 0; i < files.length; i++) {
                totalSize += files[i].size;
                
                // Check file type (optional)
                const fileType = files[i].type;
                const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
                
                if (!validTypes.includes(fileType)) {
                    Swal.fire({
                        icon: 'error',
                        title: 'Invalid File Type',
                        text: 'Only images, PDF, Word, and Excel files are allowed.',
                        confirmButtonColor: '#3085d6'
                    });
                    $(this).val('');
                    return;
                }
                
                // 5MB limit per file
                if (files[i].size > 5 * 1024 * 1024) {
                    Swal.fire({
                        icon: 'error',
                        title: 'File Too Large',
                        text: 'Each file size should not exceed 5MB.',
                        confirmButtonColor: '#3085d6'
                    });
                    $(this).val('');
                    return;
                }
            }
            
            // 20MB total limit
            if (totalSize > 20 * 1024 * 1024) {
                Swal.fire({
                    icon: 'error',
                    title: 'Total Size Too Large',
                    text: 'Total file size should not exceed 20MB.',
                    confirmButtonColor: '#3085d6'
                });
                $(this).val('');
                return;
            }
        });
        
        // When selecting a cost description in file-based mode
        $('#cost_description').on('change', function() {
            const selectedOption = $(this).find('option:selected');
            const costId = selectedOption.data('cost-id');
            
            // Store the cost reference ID
            $('#cost_reference_id').val(costId);
            
            if (!costId && $(this).val()) {
                // If no data-cost-id but there is a value, try to extract ID from value
                const costCode = $(this).val().split(' - ')[0];
                $('#cost_reference_id').val(costCode);
            }
        });
        
        // Form submission validation
        $('#fundRequestForm').submit(function(e) {
            const expenseType = $('input[name="expense_type"]:checked').val();
            
            if (expenseType === 'file') {
                const fileNumber = $('#file_number').val();
                const costDescription = $('#cost_description').val();
                
                if (!fileNumber) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        text: 'Please select a Job Number for File-based expense.',
                        confirmButtonColor: '#3085d6'
                    });
                    return false;
                }
                
                if (!costDescription) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        text: 'Please select an Expense Type for this file.',
                        confirmButtonColor: '#3085d6'
                    });
                    return false;
                }
                
                // Ensure cost_reference_id is set
                if (!$('#cost_reference_id').val() && costDescription) {
                    // Extract the code part if not already set
                    const costCode = costDescription.split(' - ')[0];
                    $('#cost_reference_id').val(costCode);
                }
            } else {
                const categoryId = $('#category_id').val();
                const description = $('#description').val();
                
                if (!categoryId) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        text: 'Please select an Office Cost Category.',
                        confirmButtonColor: '#3085d6'
                    });
                    return false;
                }
                
                if (!description.trim()) {
                    e.preventDefault();
                    Swal.fire({
                        icon: 'error',
                        title: 'Validation Error',
                        text: 'Please provide a description for this request.',
                        confirmButtonColor: '#3085d6'
                    });
                    return false;
                }
            }
            
            const amount = $('#amount').val();
            if (!amount || amount <= 0) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Validation Error',
                    text: 'Please enter a valid amount greater than zero.',
                    confirmButtonColor: '#3085d6'
                });
                return false;
            }
        });
        
        // Show success message with SweetAlert if present
        <?php if (isset($_SESSION['swal_success'])): ?>
        Swal.fire({
            icon: 'success',
            title: 'Success!',
            text: '<?php echo $_SESSION['swal_success']; ?>',
            confirmButtonColor: '#3085d6'
        });
        <?php unset($_SESSION['swal_success']); endif; ?>
        
        // Show error message with SweetAlert if present
        <?php if (isset($_SESSION['swal_error'])): ?>
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: '<?php echo $_SESSION['swal_error']; ?>',
            confirmButtonColor: '#3085d6'
        });
        <?php unset($_SESSION['swal_error']); endif; ?>
    });
    
    // Function to select expense type
    function selectExpenseType(type) {
        if (type === 'file') {
            $('#file_based_card').addClass('active');
            $('#office_based_card').removeClass('active');
            $('#file_based').prop('checked', true);
            
            // Show file-based fields and hide office-based fields
            $('#file_based_fields').show();
            $('#office_based_fields').hide();
            $('#file_description_field').show();
            $('#office_description_field').hide();
            
            // Update required attributes
            $('#file_number').prop('required', true);
            $('#category_id').prop('required', false);
            $('#cost_description').prop('required', true);
            $('#description').prop('required', false);
            
            // Force Select2 to recalculate its width
            setTimeout(function() {
                $('#file_number').select2('destroy').select2({
                    placeholder: "Please Select A Job Number",
                    allowClear: true,
                    width: '100%'
                });
                
                $('#cost_description').select2('destroy').select2({
                    placeholder: "Select Cost Type",
                    allowClear: true,
                    width: '100%'
                });
            }, 100);
            
        } else {
            $('#office_based_card').addClass('active');
            $('#file_based_card').removeClass('active');
            $('#office_based').prop('checked', true);
            
            // Show office-based fields and hide file-based fields
            $('#file_based_fields').hide();
            $('#office_based_fields').show();
            $('#file_description_field').hide();
            $('#office_description_field').show();
            
            // Update required attributes
            $('#file_number').prop('required', false);
            $('#category_id').prop('required', true);
            $('#cost_description').prop('required', false);
            $('#description').prop('required', true);
            
            // Force Select2 to recalculate its width
            setTimeout(function() {
                $('#category_id').select2('destroy').select2({
                    placeholder: "Select Expense Category",
                    allowClear: true,
                    width: '100%'
                });
            }, 100);
        }
    }
</script>
</body>
</html>