<?php
require_once __DIR__ . "/headers.php";
require_once __DIR__ . "/config.php";

/*
✅ Party Update API
✅ Method: POST
✅ Input JSON:
{
  "id": 1,
  "party_type": "customer",
  "name": "Madab Updated",
  "mobile": "01700000000",
  "address": "Dhaka",
  "opening_balance": 7000,
  "status": 1
}
*/

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    echo json_encode([
        "status" => false,
        "message" => "Invalid Request Method. Use POST."
    ]);
    exit;
}

// Read JSON input
$input = json_decode(file_get_contents("php://input"), true);

$id = intval($input["id"] ?? 0);
$party_type = trim($input["party_type"] ?? "customer");
$name = trim($input["name"] ?? "");
$mobile = trim($input["mobile"] ?? "");
$address = trim($input["address"] ?? "");
$opening_balance = floatval($input["opening_balance"] ?? 0);
$status = intval($input["status"] ?? 1);

// Validation
if ($id <= 0) {
    echo json_encode([
        "status" => false,
        "message" => "Party ID is required"
    ]);
    exit;
}

if ($name === "") {
    echo json_encode([
        "status" => false,
        "message" => "Party name is required"
    ]);
    exit;
}

// ✅ Allowed party types (security)
$allowed_types = ["customer", "supplier", "other"];
if (!in_array($party_type, $allowed_types)) {
    $party_type = "customer";
}

// ✅ Check party exists
$check = $conn->prepare("SELECT id FROM parties WHERE id=? LIMIT 1");
$check->bind_param("i", $id);
$check->execute();
$res = $check->get_result();

if ($res->num_rows == 0) {
    echo json_encode([
        "status" => false,
        "message" => "Party not found"
    ]);
    exit;
}

// ✅ Update party
$stmt = $conn->prepare("UPDATE parties SET party_type=?, name=?, mobile=?, address=?, opening_balance=?, status=? WHERE id=?");
$stmt->bind_param("ssssdii", $party_type, $name, $mobile, $address, $opening_balance, $status, $id);

if ($stmt->execute()) {
    echo json_encode([
        "status" => true,
        "message" => "Party updated successfully",
        "data" => [
            "id" => $id,
            "party_type" => $party_type,
            "name" => $name,
            "mobile" => $mobile,
            "address" => $address,
            "opening_balance" => $opening_balance,
            "status" => $status
        ]
    ]);
} else {
    echo json_encode([
        "status" => false,
        "message" => "Update failed",
        "error" => $conn->error
    ]);
}

exit;
?>