<?php
session_start();
require_once 'shikanisha.kts.php';

// Set timezone to Nairobi, Africa
date_default_timezone_set('Africa/Nairobi');

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized access']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Extract and sanitize form data
    $expenseType = trim($_POST['expense_type'] ?? '');
    $amount = filter_var($_POST['amount'] ?? 0, FILTER_VALIDATE_FLOAT);
    $user_id = $_SESSION['user_id'];
    $currentDateTime = date('Y-m-d H:i:s');

    // Validate inputs
    if (empty($expenseType) || $amount === false || $amount <= 0) {
        echo json_encode(['status' => 'error', 'message' => 'Invalid input']);
        exit;
    }

    // Begin transaction
    $conn->begin_transaction();

    try {
        // 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 FOR UPDATE";
        $stmt = $conn->prepare($shift_query);
        $stmt->bind_param("i", $user_id);
        $stmt->execute();
        $shift_result = $stmt->get_result();
        
        if ($shift_result->num_rows === 0) {
            throw new Exception("No active shift found for this user");
        }

        $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', $expenseType, $amount, $currentDateTime, $shift_id);

        if (!$stmt->execute()) {
            throw new Exception("Failed to record expense");
        }

        
        // Commit transaction
        $conn->commit();
        
        echo json_encode([
            'status' => 'success', 
            'message' => 'Expense submitted successfully',
            'data' => [
                'expense_id' => $conn->insert_id,
                'amount' => $amount,
                'shift_id' => $shift_id
            ]
        ]);

    } catch (Exception $e) {
        $conn->rollback();
        echo json_encode([
            'status' => 'error',
            'message' => $e->getMessage()
        ]);
    } finally {
        if (isset($stmt)) {
            $stmt->close();
        }
    }
} else {
    echo json_encode(['status' => 'error', 'message' => 'Invalid request method']);
}
?>