<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
require_once("definitions.php");

// Only accept POST JSON requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || empty(file_get_contents('php://input'))) {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

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

if (
    !isset($data['agent_key'], $data['firstname'], $data['lastname'], $_SESSION['email'], $data['active']) ||
    !is_numeric($data['agent_key'])
) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Missing or invalid parameters']);
    exit;
}

$agent_key = intval($data['agent_key']);
$firstname = trim($data['firstname']);
$lastname = trim($data['lastname']);
$email = trim($_SESSION['email']);
$active = $data['active'] == 1 ? 1 : 0;
$pin = isset($data['pin']) ? trim($data['pin']) : '';

// Validate email format
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Invalid email address']);
    exit;
}

if ($active === 1 && (strlen($pin) !== 4 || !ctype_digit($pin))) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Active user must have a 4-digit PIN']);
    exit;
}

$conn = new mysqli(PACKAGE_LOG_DB_SERVER, PACKAGE_LOG_DB_USER, PACKAGE_LOG_DB_PASS, PACKAGE_LOG_DB_NAME);
if ($conn->connect_error) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Database connection failed']);
    exit;
}

// Build query dynamically depending on active and pin
// If active, deleted = 0, else deleted = 1
$deleted = 1;

if ($active && $pin !== '') {
    // Update pin and active/deleted
    $stmt = $conn->prepare("UPDATE agent SET firstname = ?, lastname = ?, email = ?, pin = ?, active = ?, deleted = ? WHERE agent_key = ?");
    $stmt->bind_param("ssssiii", $firstname, $lastname, $email, $pin, $active, $deleted, $agent_key);
} else {
    // No pin update
    $stmt = $conn->prepare("UPDATE agent SET firstname = ?, lastname = ?, email = ?, active = ?, deleted = ? WHERE agent_key = ?");
    $stmt->bind_param("sssiii", $firstname, $lastname, $email, $active, $deleted, $agent_key);
}

if ($stmt->execute()) {
    echo json_encode(['success' => true]);
} else {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Failed to update user']);
}

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