<?php
// Prevent any output before JSON response
ob_start();

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

session_start();
include_once($_SERVER['DOCUMENT_ROOT'] . '/digital_pos/includes/config.php');

header('Content-Type: application/json');

// Authorization check
if (!isset($_SESSION['user_id']) || $_SESSION['role_id'] != 1) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit;
}

// Retrieve and sanitize inputs
$id = intval($_POST['id'] ?? 0);
$first_name = trim($_POST['first_name'] ?? '');
$last_name = trim($_POST['last_name'] ?? '');
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$phone = trim($_POST['phone_number'] ?? '');
$role_id = intval($_POST['role_id'] ?? 0);
$store_id = intval($_POST['store_id'] ?? 0);
$password = trim($_POST['password'] ?? '');

// Basic validation
if (!$id || !$first_name || !$last_name || !$username || !$email || !$role_id || !$store_id) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

// Fetch existing user data for audit logging
$stmtOld = $conn->prepare("SELECT first_name, last_name, username, email, phone_number, role_id, store_id FROM users WHERE id = ?");
if (!$stmtOld) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
    exit;
}
$stmtOld->bind_param("i", $id);
$stmtOld->execute();
$resultOld = $stmtOld->get_result();
if ($resultOld->num_rows === 0) {
    echo json_encode(['success' => false, 'message' => 'User not found']);
    exit;
}
$oldData = $resultOld->fetch_assoc();
$stmtOld->close();

// Check unique email/username excluding current user
$stmtUnique = $conn->prepare("
    SELECT id FROM users 
    WHERE (email = ? OR username = ?) AND id != ?
    LIMIT 1
");
if (!$stmtUnique) {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $conn->error]);
    exit;
}
$stmtUnique->bind_param("ssi", $email, $username, $id);
$stmtUnique->execute();
$stmtUnique->store_result();
if ($stmtUnique->num_rows > 0) {
    echo json_encode(['success' => false, 'message' => 'Email or username already exists.']);
    $stmtUnique->close();
    exit;
}
$stmtUnique->close();

// Prepare update statement
if (!empty($password)) {
    $hashed = password_hash($password, PASSWORD_DEFAULT);
    $sql = "UPDATE users SET first_name=?, last_name=?, username=?, email=?, phone_number=?, role_id=?, store_id=?, password=?, password_changed=1, updated_at=NOW() WHERE id=?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Failed to prepare statement: ' . $conn->error]);
        exit;
    }
    $stmt->bind_param("sssssssii", $first_name, $last_name, $username, $email, $phone, $role_id, $store_id, $hashed, $id);
} else {
    $sql = "UPDATE users SET first_name=?, last_name=?, username=?, email=?, phone_number=?, role_id=?, store_id=?, updated_at=NOW() WHERE id=?";
    $stmt = $conn->prepare($sql);
    if (!$stmt) {
        echo json_encode(['success' => false, 'message' => 'Failed to prepare statement: ' . $conn->error]);
        exit;
    }
    $stmt->bind_param("ssssssii", $first_name, $last_name, $username, $email, $phone, $role_id, $store_id, $id);
}

if ($stmt->execute()) {

    // Audit logging function
    function audit_log($conn, $userId, $roleId, $action, $details, $module, $deviceInfo) {
        $stmtLog = $conn->prepare("INSERT INTO audit_log (user_id, role_id, action, details, module, device_info) VALUES (?, ?, ?, ?, ?, ?)");
        if (!$stmtLog) return false;
        $stmtLog->bind_param("iissss", $userId, $roleId, $action, $details, $module, $deviceInfo);
        $result = $stmtLog->execute();
        $stmtLog->close();
        return $result;
    }

    // Compose details as JSON for audit log
    $changesArray = [];
    $fields = ['first_name', 'last_name', 'username', 'email', 'phone_number', 'role_id', 'store_id'];
    foreach ($fields as $field) {
        $newVal = $$field;
        $oldVal = $oldData[$field] ?? null;
        if ((string)$newVal !== (string)$oldVal) {
            $changesArray[$field] = ['old' => $oldVal, 'new' => $newVal];
        }
    }
    if (!empty($password)) {
        $changesArray['password'] = '[changed]';
    }

    $details = json_encode([
        'user_id' => $id,
        'changes' => $changesArray,
    ]);

    audit_log(
        $conn,
        $_SESSION['user_id'],
        $_SESSION['role_id'],
        "Update User",
        $details,
        "users",
        $_SERVER['HTTP_USER_AGENT'] ?? 'Unknown'
    );

    echo json_encode(['success' => true, 'message' => 'User updated']);
} else {
    echo json_encode(['success' => false, 'message' => 'Update failed: ' . $stmt->error]);
}

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

ob_end_flush();
exit;
