<?php
header("Content-Type: application/json");
require_once "../includes/functions.php"; 

// get inputs
$fullname = trim($_POST['fullname'] ?? '');
$email    = trim($_POST['email'] ?? '');
$phone    = trim($_POST['phone'] ?? '');
$pin      = trim($_POST['pin'] ?? '');
$referral = trim($_POST['referral'] ?? ''); // optional referral code

if (!$fullname || !$email || !$pin || !$phone) {
    echo json_encode(["status"=>"error", "message"=>"All fields required"]);
    exit;
}

// check if email already exists
$check = $conn->prepare("SELECT id FROM users WHERE email = ?");
$check->bind_param("s", $email);
$check->execute();
$res = $check->get_result();
if ($res->num_rows > 0) {
    echo json_encode(["status"=>"error", "message"=>"Email already registered"]);
    exit;
}

// check if phone already exists
$checkPhone = $conn->prepare("SELECT id FROM users WHERE phone = ?");
$checkPhone->bind_param("s", $phone);
$checkPhone->execute();
$resPhone = $checkPhone->get_result();
if ($resPhone->num_rows > 0) {
    echo json_encode(["status"=>"error", "message"=>"Phone already registered"]);
    exit;
}

// create hashed pin
$hashedPin = password_hash($pin, PASSWORD_DEFAULT);

// generate referral code for this user
$refCode = strtoupper(substr(md5(time() . $fullname), 0, 8));

// find referrer (if referral code provided)
$referredBy = null;
if (!empty($referral)) {
    $findRef = $conn->prepare("SELECT id FROM users WHERE referral_code = ?");
    $findRef->bind_param("s", $referral);
    $findRef->execute();
    $refResult = $findRef->get_result();
    if ($refResult->num_rows > 0) {
        $refData = $refResult->fetch_assoc();
        $referredBy = $refData['id'];
    }
}

$response = registerUser($fullname, $email, $phone, $pin, $referral);

if ($response["status"] === "success") {
    echo json_encode($response);
} else {
    echo json_encode($response);
}