<?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
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email 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'];
} else {
    header('Location: login.php');
    exit();
}

// Get expense categories from expense_ref
$exp_categories_query = "SELECT DISTINCT category FROM expense_ref ORDER BY category";
$exp_categories_result = $conn->query($exp_categories_query);
$categories = [];
while ($row = $exp_categories_result->fetch_assoc()) {
    $categories[] = $row['category'];
}

// Get expense codes
$exp_codes_query = "SELECT code, description FROM expense_ref ORDER BY code";
$exp_codes_result = $conn->query($exp_codes_query);
$codes = [];
while ($row = $exp_codes_result->fetch_assoc()) {
    $codes[] = $row;
}

// Get active shipment files for reference
$files_query = "SELECT file_number FROM files ORDER BY created_date DESC";
$files_result = $conn->query($files_query);
$files = [];
while ($row = $files_result->fetch_assoc()) {
    $files[] = $row['file_number'];
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // Generate expense number (EXP/YYYY/MM/XXXX)
        $year = date('Y');
        $month = date('m');
        $sql = "SELECT exp_no FROM expenses WHERE exp_no LIKE 'EXP/$year/$month/%' ORDER BY id DESC LIMIT 1";
        $result = $conn->query($sql);
        if ($result->num_rows > 0) {
            $last_exp = $result->fetch_assoc()['exp_no'];
            $last_number = intval(substr($last_exp, -4));
            $new_number = str_pad($last_number + 1, 4, '0', STR_PAD_LEFT);
        } else {
            $new_number = '0001';
        }
        $exp_no = "EXP/$year/$month/$new_number";

        // Validate and sanitize input
        $office_cost = filter_input(INPUT_POST, 'office_cost', FILTER_SANITIZE_STRING);
        $description = filter_input(INPUT_POST, 'description', FILTER_SANITIZE_STRING);
        $amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
        $currency = filter_input(INPUT_POST, 'currency', FILTER_SANITIZE_STRING);
        $pay_mode = filter_input(INPUT_POST, 'pay_mode', FILTER_SANITIZE_STRING);
        $file_number = filter_input(INPUT_POST, 'file_number', FILTER_SANITIZE_STRING);

        if (!$amount) {
            throw new Exception("Invalid amount");
        }

        // Insert expense record
        $sql = "INSERT INTO expenses (exp_no, office_cost, description, amount, currency, 
                                    pay_mode, file_number, user_id, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Pending')";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param('sssdsssi', 
            $exp_no, $office_cost, $description, $amount, 
            $currency, $pay_mode, $file_number, $user_id
        );

        if (!$stmt->execute()) {
            throw new Exception("Failed to save expense: " . $stmt->error);
        }

        $_SESSION['success_message'] = "Expense recorded successfully. Expense No: $exp_no";
        header('Location: expense_list.php');
        exit();

    } catch (Exception $e) {
        $_SESSION['error_message'] = $e->getMessage();
    }
}

?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Capture Expense')); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    
    <style>
        .required:after {
            content: " *";
            color: red;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Expenses', 'title' => 'Capture Expense')); ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <?php 
                            echo $_SESSION['error_message'];
                            unset($_SESSION['error_message']);
                            ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header align-items-center d-flex">
                                    <h4 class="card-title mb-0 flex-grow-1">Expense Details</h4>
                                </div>
                                
                                <div class="card-body">
                                    <form action="" method="POST" id="expenseForm">
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label class="form-label required">Expense Category</label>
                                                <select class="form-select" name="office_cost" required>
                                                    <option value="">Select Category</option>
                                                    <?php foreach ($categories as $category): ?>
                                                        <option value="<?php echo htmlspecialchars($category); ?>">
                                                            <?php echo htmlspecialchars($category); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>

                                            <div class="col-md-6">
                                                <label class="form-label required">Expense Code</label>
                                                <select class="form-select" name="expense_code" required>
                                                    <option value="">Select Code</option>
                                                    <?php foreach ($codes as $code): ?>
                                                        <option value="<?php echo htmlspecialchars($code['code']); ?>">
                                                            <?php echo htmlspecialchars($code['code'] . ' - ' . $code['description']); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-12">
                                                <label class="form-label required">Description</label>
                                                <textarea class="form-control" name="description" rows="3" required></textarea>
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-4">
                                                <label class="form-label required">Amount</label>
                                                <input type="number" class="form-control" name="amount" step="0.01" required>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label class="form-label required">Currency</label>
                                                <select class="form-select" name="currency" required>
                                                    <option value="$">USD</option>
                                                    <option value="Tsh">TZS</option>
                                                </select>
                                            </div>
                                            
                                            <div class="col-md-4">
                                                <label class="form-label required">Payment Mode</label>
                                                <select class="form-select" name="pay_mode" required>
                                                    <option value="Cash">Cash</option>
                                                    <option value="Bank">Bank Transfer</option>
                                                    <option value="Mobile">Mobile Money</option>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="row mb-3">
                                            <div class="col-md-12">
                                                <label class="form-label">Related File Number</label>
                                                <select class="form-select" name="file_number">
                                                    <option value="">Select File Number</option>
                                                    <?php foreach ($files as $file): ?>
                                                        <option value="<?php echo htmlspecialchars($file); ?>">
                                                            <?php echo htmlspecialchars($file); ?>
                                                        </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                        </div>

                                        <div class="row">
                                            <div class="col-md-12">
                                                <button type="submit" class="btn btn-primary">Submit Expense</button>
                                                <a href="expense_list.php" class="btn btn-secondary">Cancel</a>
                                            </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>
    <!--select2 cdn-->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    <script src="assets/js/pages/select2.init.js"></script>
    <script>

        $(document).ready(function() {

            // Choices.js initialization for select elements
    document.querySelectorAll('select.form-select').forEach(select => {
        if (select.id && !select.classList.contains('js-example-basic-single') && !select.id.startsWith('modal')) {
            new Choices(select, {
                searchEnabled: true,
                searchChoices: true,
                searchPlaceholderValue: 'Search...'
            });
        }
    });
            
            // Form validation
            $('#expenseForm').on('submit', function(e) {
                var amount = $('input[name="amount"]').val();
                if (amount <= 0) {
                    e.preventDefault();
                    alert('Amount must be greater than 0');
                    return false;
                }
            });
        });
        // Initialize page when loaded
        $(document).ready(function() {
                // Initialize Select2 for all select elements with the specific class
                $('.js-example-basic-single').select2({
                    placeholder: "Select an option",
                    allowClear: true
                });
            });
    </script>
</body>
</html>