<?php
include('db_connection.php');

function generateIncomeCode($conn) {
    $prefix = "INC";
    $date = date("Ymd");

    $query = "SELECT COUNT(*) as count FROM income WHERE DATE(date) = ?";
    $stmt = $conn->prepare($query);

    $today = date("Y-m-d");
    $stmt->bind_param("s", $today);

    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();

    $count = $row['count'] + 1;
    $stmt->close();

    return $prefix . $date . sprintf("%04d", $count);
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    $source = $_POST['source'];
    $amount = $_POST['amount'];
    $date = $_POST['date'];
    $term = $_POST['term'];
    $session = $_POST['session'];

    // ✅ Generate income code
    $income_code = generateIncomeCode($conn);

    // ✅ Insert into database
    $sql = "INSERT INTO income (income_code, source, amount, date, term, session) 
            VALUES (?, ?, ?, ?, ?, ?)";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("ssdsss", $income_code, $source, $amount, $date, $term, $session);

    if ($stmt->execute()) {
        header('Location: view_transactions.php?success=1');
    } else {
        echo "Error: " . $stmt->error;
    }

    $stmt->close();
}

$conn->close();
?>