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

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

function sendJson($data){
    header("Content-Type: application/json; charset=UTF-8");
    echo json_encode($data);
    exit;
}

// ✅ Only POST allowed
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    sendJson([
        "status" => false,
        "message" => "Invalid Request Method. Use POST."
    ]);
}

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

if (!$input) {
    sendJson([
        "status" => false,
        "message" => "Invalid JSON input"
    ]);
}

$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 ($name === "") {
    sendJson(["status" => false, "message" => "Party name is required"]);
}

$allowed_types = ["customer", "supplier", "other"];
if (!in_array($party_type, $allowed_types)) {
    $party_type = "customer";
}

// ✅ Insert Party
try {
    $stmt = $conn->prepare("
        INSERT INTO parties (party_type, name, mobile, address, opening_balance, status)
        VALUES (?, ?, ?, ?, ?, ?)
    ");

    if (!$stmt) {
        sendJson([
            "status" => false,
            "message" => "Prepare failed",
            "error" => $conn->error
        ]);
    }

    $stmt->bind_param("ssssdi", $party_type, $name, $mobile, $address, $opening_balance, $status);

    if ($stmt->execute()) {
        sendJson([
            "status" => true,
            "message" => "Party Added Successfully ✅",
            "party_id" => $stmt->insert_id
        ]);
    } else {
        sendJson([
            "status" => false,
            "message" => "Insert failed",
            "error" => $stmt->error
        ]);
    }

} catch (Exception $e) {
    sendJson([
        "status" => false,
        "message" => "Server error",
        "error" => $e->getMessage()
    ]);
}