<? require_once("definitions.php"); ?><?php
session_start();
header('Content-Type: application/json');

// Database connection info
$servername = PACKAGE_LOG_DB_SERVER;
$username = PACKAGE_LOG_DB_USER;
$password = PACKAGE_LOG_DB_PASS;
$dbname = PACKAGE_LOG_DB_NAME;

// Validate required session variables
if (!isset($_SESSION['email'], $_SERVER['REMOTE_ADDR'], $_SESSION['signature'])) {
    echo json_encode(['success' => false, 'message' => 'Required session variables not set']);
    exit;
}

$email = $_SESSION['email'];
$loggedip = $_SERVER['REMOTE_ADDR'];
$token = $_SESSION['signature']; // Assuming this is token stored in session as 'signature'

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    echo json_encode(['success' => false, 'message' => 'Invalid input']);
    exit;
}

$firstname = trim($input['firstname'] ?? '');
$lastname = trim($input['lastname'] ?? '');
$pin = trim($input['pin'] ?? '');

if ($firstname === '' || $lastname === '' || !preg_match('/^\d{4,}$/', $pin)) {
    echo json_encode(['success' => false, 'message' => 'Invalid input data']);
    exit;
}

// Connect to database
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    echo json_encode(['success' => false, 'message' => "DB Connection failed: " . $conn->connect_error]);
    exit;
}

// Prepare statement to fetch store_key and franchise_key from signature table
$stmt = $conn->prepare("SELECT store_key, franchise_key FROM signature WHERE loggedip = ? AND token = ? LIMIT 1");
if (!$stmt) {
    echo json_encode(['success' => false, 'message' => "Prepare failed: " . $conn->error]);
    exit;
}

$stmt->bind_param("ss", $loggedip, $token);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'No matching signature found']);
    $stmt->close();
    $conn->close();
    exit;
}

$row = $result->fetch_assoc();
$store_key = intval($row['store_key']);
$franchise_key = intval($row['franchise_key']);

$stmt->close();

// Fixed password
$password = "c747b5263bc2bdc777a4e1189d331a74d4d209b04b8d574fb312951497d966c2007c7eaef5880ac9bbcc7db80bce782572fe909337ab012c7d27275a8b16fc23";

$access = 1;        // Default access level, adjust as needed
$loginattempts = 0;
$active = 1;        // Set user as active by default
$deleted = 1;

// Prepare insert statement for agent table
$insert_stmt = $conn->prepare("INSERT INTO agent (franchise_key, store_key, firstname, lastname, email, agent.password, pin, access, loginattempts, active, deleted) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
if (!$insert_stmt) {
    echo json_encode(['success' => false, 'message' => "Prepare failed: " . $conn->error]);
    $conn->close();
    exit;
}

$insert_stmt->bind_param(
    "iissssiiiii",
    $franchise_key,
    $store_key,
    $firstname,
    $lastname,
    $email,
    $password,
    $pin,
    $access,
    $loginattempts,
    $active,
    $deleted
);

if ($insert_stmt->execute()) {
    echo json_encode(['success' => true]);
} else {
    echo json_encode(['success' => false, 'message' => $insert_stmt->error]);
}

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