<?php
session_start();
include_once "shikanisha.kts.php";

if (isset($_POST['expense'])) {
    // Validate and sanitize inputs
    $name = mysqli_real_escape_string($conn, $_POST['expense_type']);
    $amount = floatval($_POST['amount']);
    $user_id = $_SESSION['user_id'];
    date_default_timezone_set("Africa/Nairobi");
    $date = date('Y-m-d H:i:s');

    // Get the user's active shift
    $shift_query = "SELECT shift_id FROM shifts WHERE employee_id = ? AND status = 'active' ORDER BY start_time DESC LIMIT 1";
    $stmt = $conn->prepare($shift_query);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $shift_result = $stmt->get_result();
    
    if ($shift_result->num_rows > 0) {
        $shift = $shift_result->fetch_assoc();
        $shift_id = $shift['shift_id'];

        // Insert expense with shift_id
        $sql = "INSERT INTO expenses (expense_name, expense_amount, date_incurred, shift_id) 
                VALUES (?, ?, ?, ?)";
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("sdsi", $name, $amount, $date, $shift_id);
        
        if ($stmt->execute()) {
            $_SESSION['success'] = "Expense recorded successfully";
            header("Location: ../expenses.php");
            exit();
        } else {
            $_SESSION['error'] = "Error recording expense: " . $conn->error;
            header("Location: ../expenses.php");
            exit();
        }
    } else {
        $_SESSION['error'] = "No active shift found for this user";
        header("Location: ../expenses.php");
        exit();
    }
}
?>