<?php
header("Content-Type: application/json");
require_once '../config/db.php'; // Ensure this path correctly points to your DB connection

/**
 * 1. DATA CAPTURE & SANITIZATION
 * We capture the 8 primary fields plus the custom rank input.
 */
$name    = $_POST['name'] ?? '';
$email   = $_POST['email'] ?? '';
$mobile  = $_POST['mobile'] ?? '';
$city    = $_POST['city'] ?? '';
$state   = $_POST['state'] ?? '';
$gender  = $_POST['gender'] ?? 'Male';
$company = intval($_POST['company'] ?? 0); // Stored as INT

/**
 * 2. RANK LOGIC
 * If the user selected "Custom", we prioritize the 'custom_rank' text field.
 */
$selected_rank = $_POST['rank'] ?? 'Associate';
$custom_rank   = $_POST['custom_rank'] ?? '';
$final_rank    = ($selected_rank === 'Custom' && !empty($custom_rank)) ? $custom_rank : $selected_rank;

/**
 * 3. SECURITY (PASSWORD HASHING)
 * The 'pin' column in your DB stores hashed strings.
 */
$plain_pin  = $_POST['pin'] ?? '';
if (empty($plain_pin)) {
    echo json_encode(["success" => false, "message" => "Pin is required."]);
    exit;
}
$hashed_pin = password_hash($plain_pin, PASSWORD_DEFAULT);

/**
 * 4. VALIDATION
 * Ensure the email is not already registered in the 'grovia' database.
 */
$check = $conn->prepare("SELECT id FROM users WHERE email = ?");
$check->bind_param("s", $email);
$check->execute();
if ($check->get_result()->num_rows > 0) {
    echo json_encode(["success" => false, "message" => "Error: This email is already in use."]);
    exit;
}

/**
 * 5. DATABASE INSERTION
 * We map to exactly 9 columns. 'id' and 'created_at' are handled by MySQL.
 */
$sql = "INSERT INTO users (name, email, city, state, mobile, pin, gender, rank, company) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

$stmt = $conn->prepare($sql);

// Binding types: 8 strings (s) and 1 integer (i) for the company ID
$stmt->bind_param("ssssssssi", 
    $name, 
    $email, 
    $city, 
    $state, 
    $mobile, 
    $hashed_pin, 
    $gender, 
    $final_rank, 
    $company
);

if ($stmt->execute()) {
    echo json_encode([
        "success" => true, 
        "message" => "Account for " . htmlspecialchars($name) . " created successfully!"
    ]);
} else {
    echo json_encode([
        "success" => false, 
        "message" => "Database Error: " . $conn->error
    ]);
}

$stmt->close();
$conn->close();