<?php
// finalize-registration.php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
ini_set('display_errors', 1);
error_reporting(E_ALL);

// DB Connection
$conn = new mysqli("localhost", "gobolcha_gobolchain", "@Jibala1997", "gobolcha_gobolchain");
if ($conn->connect_error) {
    die(json_encode(["status" => "error", "message" => "Database connection failed."]));
}

// Collect form data
$firstName = trim($_POST['firstName'] ?? '');
$middleName = trim($_POST['middleName'] ?? '');  // This one is NOT required in your PHP validation
$lastName = trim($_POST['lastName'] ?? '');
$dob = trim($_POST['dob'] ?? '');               // Optional
$country = trim($_POST['country'] ?? '');
$email = trim($_POST['email'] ?? '');
$password = $_POST['password'] ?? '';
$confirmPassword = $_POST['confirmPassword'] ?? '';
$confirmPassword = $_POST['confirmPassword'] ?? '';
$referrer = trim($_POST['referrer'] ?? '');
$kycStatus = "Pending";

// Validate required fields
if (empty($firstName) || empty($lastName) || empty($country) || empty($email) || empty($password) || empty($confirmPassword)) {
    die(json_encode(["status" => "error", "message" => "Please fill in all required fields."]));
}

if ($password !== $confirmPassword) {
    die(json_encode(["status" => "error", "message" => "Passwords do not match."]));
}

// Check if user already exists
$stmt = $conn->prepare("SELECT id FROM users WHERE email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();

if ($stmt->num_rows > 0) {
    die(json_encode(["status" => "error", "message" => "User already exists with this email."]));
}
$stmt->close();

// Insert new user
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);

$insert = $conn->prepare("INSERT INTO users 
(first_name, middle_name, surname, dob, country, email, password, referred_by, kyc_status) 
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");

$insert->bind_param(
    "sssssssss",
    $firstName,
    $middleName,
    $lastName,
    $dob,
    $country,
    $email,
    $hashedPassword,
    $referrer,
    $kycStatus
);

if ($insert->execute()) {
    // Give 0.02 GBL referral reward to the referrer (if any)
    if (!empty($referrer)) {
        $reward = 0.02;
        $updateReferrer = $conn->prepare("UPDATE users SET referral_balance = referral_balance + ? WHERE email = ?");
        $updateReferrer->bind_param("ds", $reward, $referrer);
        $updateReferrer->execute();
        $updateReferrer->close();
    }
    
    require $_SERVER['DOCUMENT_ROOT'] . '/welcome_email.php';
sendWelcomeEmail($email, $firstName);

    header("Location: registration-success.html");
    exit();
} else {
    die(json_encode(["status" => "error", "message" => "Failed to register user."]));
}

?>