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

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

// 1) Pokea POST data
$branch_id  = isset($_POST['branch_id']) ? intval($_POST['branch_id']) : 0;
$date       = isset($_POST['date']) ? $_POST['date'] : '';
$new_amount = isset($_POST['new_amount']) ? floatval($_POST['new_amount']) : 0;

// 2) Validate inputs
if ($branch_id == 0 || empty($date) || $new_amount < 0) {
    echo json_encode([
        "success" => false,
        "message" => "Missing or invalid required fields"
    ]);
    exit;
}

// 3) Angalia kama entry ya closed_balance inayo exist kwa branch_id + date
$checkSql = "
    SELECT id 
      FROM closed_balance 
     WHERE branch_id = ? 
       AND DATE(date) = ?
    LIMIT 1
";
$stmtCheck = $conn->prepare($checkSql);
$stmtCheck->bind_param("is", $branch_id, $date);
$stmtCheck->execute();
$resCheck = $stmtCheck->get_result();

if ($resCheck && $resCheck->num_rows > 0) {
    // 4A) Ikiwa record ipo, fanya UPDATE
    $row = $resCheck->fetch_assoc();
    $cbId = intval($row['id']);

    $updateSql = "
      UPDATE closed_balance 
         SET amount = ? 
       WHERE id = ?
    ";
    $stmtUpd = $conn->prepare($updateSql);
    $stmtUpd->bind_param("di", $new_amount, $cbId);

    if ($stmtUpd->execute()) {
        echo json_encode([
            "success" => true,
            "message" => "Closed balance updated successfully"
        ]);
    } else {
        echo json_encode([
            "success" => false,
            "message" => "Failed to update: " . $stmtUpd->error
        ]);
    }
    $stmtUpd->close();
} else {
    // 4B) Ikiwa record haipo, weka INSERT mpya
    $insertSql = "
      INSERT INTO closed_balance (amount, branch_id, date) 
      VALUES (?, ?, ?)
    ";
    $stmtIns = $conn->prepare($insertSql);
    if (!$stmtIns) {
        echo json_encode([
            "success" => false,
            "message" => "Prepare INSERT failed: " . $conn->error
        ]);
        exit;
    }
    $stmtIns->bind_param("dis", $new_amount, $branch_id, $date);

    if ($stmtIns->execute()) {
        echo json_encode([
            "success" => true,
            "message" => "Closed balance inserted successfully"
        ]);
    } else {
        echo json_encode([
            "success" => false,
            "message" => "Failed to insert: " . $stmtIns->error
        ]);
    }
    $stmtIns->close();
}

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