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

$table = 'users';

$getJson = file_get_contents('php://input');
$json = json_decode($getJson);

// Pastikan input yang dibutuhkan tersedia
if (!isset($json->codex)) {
	echo json_encode(["error" => true, "message" => "Username dan kode verifikasi diperlukan"]);
	exit;
}

$userx = isset($json->userx) ? $json->userx : null;
$phonex = isset($json->phonex) ? $json->phonex : null;
$verifyCode = $json->codex;
$newPass = isset($json->newpass) ? $json->newpass : null;

if ($userx != null) {
	$stmt = $connect->prepare("SELECT username, auth_sms FROM $table WHERE username=? AND auth_sms=?");
	$stmt->bind_param("ss", $userx, $verifyCode);
	$stmt->execute();
	$result = $stmt->get_result();
	$cekverify = $result->num_rows;
	$hasil = $result->fetch_assoc();
} else {
	$stmt = $connect->prepare("SELECT username, auth_sms FROM $table WHERE phone=? AND auth_sms=?");
	$stmt->bind_param("ss", $phonex, $verifyCode);
	$stmt->execute();
	$result = $stmt->get_result();
	$cekverify = $result->num_rows;
	$hasil = $result->fetch_assoc();
}


if ($cekverify > 0) {
	if ($newPass != null) {

		$stmt = $connect->prepare("UPDATE $table SET password=MD5(?) WHERE username=?");
		$stmt->bind_param("ss", $newPass, $userx);
		$stmt->execute();

		$response = [
			"error" => false,
			"message" => "Password berhasil diperbarui",
			"data" => $hasil
		];
	} else {
		if ($userx != null) {
			$connect->query("UPDATE " . $table . " SET register_confirmation=1 WHERE username='" . $userx . "' and auth_sms='" . $verifyCode . "'");
		}
		$response = [
			"error" => false,
			"message" => "Kode verifikasi benar",
			"data" => $hasil
		];
	}
} else {
	$response = [
		"error" => true,
		"message" => "Kode verifikasi salah",
		"data" => null
	];
}

// Mengirimkan response JSON
echo json_encode($response);
