<?php
header("Content-Type: application/json");
require_once '../config/db.php';

$id = intval($_POST['id']);
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];
$gender = $_POST['gender'];
$city = $_POST['city'];
$state = $_POST['state'];
$rank = $_POST['rank'];
$company = intval($_POST['company']);

/**
 * 2. CUSTOM RANK LOGIC
 * If "Custom" is picked, we use the text input.
 */
$selected_rank = $_POST['rank'] ?? 'Associate';
$custom_rank   = $_POST['custom_rank'] ?? '';
$final_rank    = ($selected_rank === 'Custom' && !empty($custom_rank)) ? $custom_rank : $selected_rank;

/**
 * 3. UPDATE DATABASE
 * We update exactly 8 columns (Password/Pin is usually handled in a separate 'Reset' function).
 */
$sql = "UPDATE users SET 
        name = ?, 
        email = ?, 
        mobile = ?, 
        gender = ?, 
        city = ?, 
        state = ?, 
        rank = ?, 
        company = ? 
        WHERE id = ?";

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

// Types: 7 strings (s), 2 integers (ii for company and id)
$stmt->bind_param("sssssssii", 
    $name, 
    $email, 
    $mobile, 
    $gender, 
    $city, 
    $state, 
    $final_rank, 
    $company, 
    $id
);

if ($stmt->execute()) {
    echo json_encode(["success" => true, "message" => "Changes saved for $name. Redirecting..."]);
} else {
    echo json_encode(["success" => false, "message" => "Database Error: " . $conn->error]);
}

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