<?php
session_start();
if (!isset($_SESSION['admin'])) {
    header('HTTP/1.1 403 Forbidden');
    echo json_encode(['success' => false, 'message' => 'Access denied']);
    exit;
}

$dbFile = '../chat_history.sqlite';
$db = new SQLite3($dbFile);

$action = $_POST['action'] ?? '';

switch ($action) {
    case 'create':
    case 'update':
        $id = $_POST['id'] ?? '';
        $username = $_POST['username'] ?? '';
        $password = $_POST['password'] ?? '';
        $profileId = $_POST['profile_id'] ?? null;

        if (empty($username)) {
            echo json_encode(['success' => false, 'message' => 'Username is required']);
            exit;
        }

        if ($action === 'create') {
            if (empty($password)) {
                echo json_encode(['success' => false, 'message' => 'Password is required for new users']);
                exit;
            }
            $stmt = $db->prepare('INSERT INTO users (username, password, profile_id) VALUES (:username, :password, :profile_id)');
        } else {
            $stmt = $db->prepare('UPDATE users SET username = :username, profile_id = :profile_id WHERE id = :id');
            $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        }

        $stmt->bindValue(':username', $username, SQLITE3_TEXT);
        $stmt->bindValue(':profile_id', $profileId, $profileId ? SQLITE3_INTEGER : SQLITE3_NULL);

        if ($action === 'create' || !empty($password)) {
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);
            $stmt->bindValue(':password', $hashedPassword, SQLITE3_TEXT);
        }

        $result = $stmt->execute();

        if ($result) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Database error']);
        }
        break;

    case 'delete':
        $id = $_POST['id'] ?? '';
        if (empty($id)) {
            echo json_encode(['success' => false, 'message' => 'User ID is required']);
            exit;
        }

        $stmt = $db->prepare('DELETE FROM users WHERE id = :id');
        $stmt->bindValue(':id', $id, SQLITE3_INTEGER);
        $result = $stmt->execute();

        if ($result) {
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'message' => 'Database error']);
        }
        break;

    default:
        echo json_encode(['success' => false, 'message' => 'Invalid action']);
        break;
}