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

date_default_timezone_set('Africa/Dar_es_Salaam');
include '../../config.php';

// Pokea data kutoka POST
$branch_name = isset($_POST['branch_name']) ? $_POST['branch_name'] : '';
$location = isset($_POST['location']) ? $_POST['location'] : '';
$interest = isset($_POST['interest']) ? floatval($_POST['interest']) : 0;
$form_fee = isset($_POST['form_fee']) ? floatval($_POST['form_fee']) : 0;
$user_id = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;

// Hakikisha fields muhimu zipo
if (empty($branch_name) || empty($location) || $interest == 0 || $user_id == 0) {
    echo json_encode(["success" => false, "message" => "Missing required fields"]);
    exit;
}

// SQL ya kuingiza tawi pamoja na ada ya fomu
$sql = "INSERT INTO branches (branch_name, location, interest, form_fee, user_id) VALUES (?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);

if (!$stmt) {
    echo json_encode(["success" => false, "message" => "SQL Error: " . $conn->error]);
    exit;
}

// Funga data kwenye query
$stmt->bind_param("ssddi", $branch_name, $location, $interest, $form_fee, $user_id);

// Tekeleza query
if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Branch added successfully"]);
} else {
    echo json_encode(["success" => false, "message" => "Failed to add branch: " . $stmt->error]);
}

// Funga statement na connection
$stmt->close();
$conn->close();
?>
