<?php
// update_batch_status.php

error_reporting(E_ALL);
ini_set('display_errors', 1);

include "includes/db_connect.php";
include "includes/auth.php";
checkAdmin();

// ----------------------
// Read POST data
// ----------------------
$batchID = isset($_POST['batch_id']) ? mysqli_real_escape_string($conn, $_POST['batch_id']) : '';
$status  = isset($_POST['status']) ? mysqli_real_escape_string($conn, $_POST['status']) : '';

$validStatuses = ['OPEN', 'CLOSED', 'PAID'];

if (!$batchID || !in_array($status, $validStatuses)) {
    die("Invalid batch ID or status.");
}

// ----------------------
// Update batch status
// ----------------------
$update = "
UPDATE settlement_batches
SET status='$status'
WHERE batch_id='$batchID'
LIMIT 1
";

if (mysqli_query($conn, $update)) {
    $msg = "Batch $batchID status updated to $status successfully.";
} else {
    $msg = "Failed to update batch status: " . mysqli_error($conn);
}

// ----------------------
// Redirect back to settlement page with message
// ----------------------
header("Location: madr_net_settlement.php?to_country=" . urlencode($_POST['to_country'] ?? '') .
       "&from_date=" . urlencode($_POST['from_date'] ?? '') .
       "&to_date=" . urlencode($_POST['to_date'] ?? '') .
       "&msg=" . urlencode($msg));
exit;
