<?php
session_start();
include 'database.php';
header('Content-Type: application/json');

if (!isset($_SESSION['username'])) {
    http_response_code(401);
    echo json_encode(["success" => false, "message" => "Unauthorized access."]);
    exit;
}

ini_set('display_errors', 1);
error_reporting(E_ALL);

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    response(false, "Invalid request method. POST required.");
}

$data = json_decode(file_get_contents("php://input"), true);
if (!$data || !is_array($data)) {
    response(false, "Invalid JSON data received. Ensure Content-Type is 'application/json'.");
}

$requiredFields = ['apiKey', 'username', 'type', 'status', 'expDate', 'limit'];
foreach ($requiredFields as $field) {
    if (empty($data[$field])) {
        response(false, "Missing required field: $field");
    }
}

$apiKey = trim($data['apiKey']);
$username = trim($data['username']);
$type = trim($data['type']);
$status = trim($data['status']);
$expDate = trim($data['expDate']);
$limitInput = $data['limit'];

if (strcasecmp(strval($limitInput), 'UNLIMITED') === 0) {
    $limit = 99999999;
    $newBalance = 99999999;
} elseif (is_numeric($limitInput) && $limitInput >= 0 && $limitInput < 99999999) {
    $limit = intval($limitInput);
    $newBalance = intval($limitInput);
} else {
    response(false, "Invalid data: 'limit' must be numeric and non-negative or 'UNLIMITED'.");
}

if (!DateTime::createFromFormat('Y-m-d H:i:s', $expDate)) {
    response(false, "Invalid 'expDate' format. Use 'Y-m-d H:i:s'.");
}

$updateSql = "UPDATE users SET username = ?, apiKey = ?, type = ?, status = ?, expiryDate = ?, `limit` = ?, balance = ? WHERE apiKey = ?";
$updateStmt = $conn->prepare($updateSql);
if (!$updateStmt) {
    error_log("SQL Prepare Error: " . $conn->error);
    response(false, "Database error: Unable to prepare update statement.");
}

$updateStmt->bind_param("sssssiis", $username, $apiKey, $type, $status, $expDate, $limit, $newBalance, $apiKey);
if ($updateStmt->execute()) {
    $affectedRows = $updateStmt->affected_rows;
    if ($affectedRows > 0) {
        response(true, "User details updated successfully.", ["affectedRows" => $affectedRows]);
    } else {
        response(false, "No changes made. Details are already up-to-date or the user does not exist.");
    }
} else {
    error_log("SQL Execute Error: " . $updateStmt->error);
    response(false, "Failed to update user details.");
}

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

function response($success, $message, $data = []) {
    http_response_code($success ? 200 : 400);
    echo json_encode(array_merge(["success" => $success, "message" => $message], $data), JSON_PRETTY_PRINT);
    exit;
}
?>