<?php 
require dirname(dirname(__FILE__)).'/inc/config.php';
require dirname(dirname(__FILE__)).'/inc/FunctionQuery.php';
require dirname(dirname(__FILE__)).'/inc/keyvaliation.php';
header('Content-type: application/json');

$data = json_decode(file_get_contents('php://input'), true);

if (empty($data['name']) || empty($data['mobile']) || empty($data['password']) || empty($data['ccode']) || empty($data['email'])) {
    $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Something Went Wrong!");
    echo json_encode($returnArr);
    exit;
}

$name = strip_tags(mysqli_real_escape_string($service, $data['name']));
$email = strip_tags(mysqli_real_escape_string($service, $data['email']));
$mobile = strip_tags(mysqli_real_escape_string($service, $data['mobile']));
$ccode = strip_tags(mysqli_real_escape_string($service, $data['ccode']));
$password = strip_tags(mysqli_real_escape_string($service, $data['password']));

$checkmob = $service->query("SELECT id FROM tbl_lowner WHERE mobile = '".$mobile."' LIMIT 1");
$checkemail = $service->query("SELECT id FROM tbl_lowner WHERE email = '".$email."' LIMIT 1");

if ($checkmob->num_rows > 0) {
    $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Mobile Number Already Used!");
} else if ($checkemail->num_rows > 0) {
    $returnArr = array("ResponseCode"=>"401","Result"=>"false","ResponseMsg"=>"Email Address Already Used!");
} else {
    $timestamp = date("Y-m-d H:i:s");
    $table = "tbl_lowner";
    $field_values = array("name","email","mobile","rdate","password","ccode");
    $data_values = array("$name","$email","$mobile","$timestamp","$password","$ccode");

    $h = new FunctionQuery($service);
    $insert_id = $h->serviceinsertdata_Api($field_values, $data_values, $table);

    // Fallback: if your FunctionQuery doesn't return insert_id properly
    if (empty($insert_id) || !is_numeric($insert_id)) {
        $insert_id = $service->insert_id;
    }

    // Fetch exact new record by its unique ID
    $user = $service->query("SELECT * FROM tbl_lowner WHERE id = '".$insert_id."' LIMIT 1")->fetch_assoc();

    $returnArr = array(
        "UserLogin" => $user,
        "ResponseCode" => "200",
        "Result" => "true",
        "ResponseMsg" => "Sign Up Done Successfully!"
    );
}

echo json_encode($returnArr);
?>
