<?php
// Replace these variables with your actual database credentials
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "ams";

// Create a connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check the connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Sample data (replace these with your actual form data)
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$phone = $_POST['phone'];
$region = $_POST['region'];
$tin = $_POST['tin'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT); // Hash the password
$tc = $_POST['tc'];

// Generate a unique 8-digit code
$code = generateUniqueCode($conn);

// SQL query with a prepared statement
$sql = "INSERT INTO agents (fname, lname, phone, region, tin, password, tc, code) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);

// Bind parameters
$stmt->bind_param("ssssssss", $fname, $lname, $phone, $region, $tin, $password, $tc, $code);

// Execute the statement
if ($stmt->execute()) {
    echo "Data inserted successfully.";
} else {
    echo "Error: " . $stmt->error;
}

// Close the statement and connection
$stmt->close();
$conn->close();

// Function to generate a unique 8-digit code
function generateUniqueCode($conn) {
    $code = generateCode();

    // Check if the code already exists in the database
    $stmt = $conn->prepare("SELECT COUNT(*) FROM agents WHERE code = ?");
    $stmt->bind_param("s", $code);
    $stmt->execute();
    $stmt->bind_result($count);
    $stmt->fetch();
    $stmt->close();

    // If the code exists, generate a new one
    if ($count > 0) {
        return generateUniqueCode($conn);
    }

    return $code;
}

// Function to generate an 8-digit code
function generateCode() {
    return str_pad(mt_rand(1, 99999999), 8, '0', STR_PAD_LEFT);
}
?>
