<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");

// Set timezone ya Dar es Salaam
date_default_timezone_set('Africa/Dar_es_Salaam');
include '../config.php';


// Pokea data kutoka POST
$price = isset($_POST['price']) ? $_POST['price'] : null;
$description = isset($_POST['description']) ? $_POST['description'] : null;
$date = isset($_POST['date']) ? $_POST['date'] : date('Y-m-d H:i:s');
$user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
$branch_id = isset($_POST['branch_id']) ? intval($_POST['branch_id']) : 0;

// Hakikisha data zote zipo
if ($price === null || $description === null || $user_id == 0 || $branch_id == 0) {
    echo json_encode(["success" => false, "message" => "Missing required fields"]);
    exit;
}

// Andaa statement ya SQL
$sql = "INSERT INTO expenditures (price, description, date, user_id, branch_id) VALUES (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("dssii", $price, $description, $date, $user_id, $branch_id);

if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Expense added successfully"]);
} else {
    echo json_encode(["success" => false, "message" => "Error: " . $stmt->error]);
}

$stmt->close();
$conn->close();
?>
