<?php
error_reporting(255);
ini_set('display_errors', 'on');

header('Content-type: text/html; charset=utf-8');

require_once('utils.php');

configure_session_lifetime(12);

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

if(!isset($_SESSION['email'])) {
  header("location:connect.php?signin=connect");
  exit;
}

$active_order_content = Array();
$userid=$_SESSION['usid'];


//-------------------------------------------------------------------------------------
$api = (isset($_REQUEST["api"]) && $_REQUEST["api"] == 1);
$mode = isset($_REQUEST["mode"]) ? $_REQUEST["mode"] : "all";

$res = "";
$msg = "info";
$action = isset($_REQUEST["action"]) ? $_REQUEST["action"] : "none";

if ($api) {
    if ($action == "get_profil") {
        $res = Array();
        $dbres = do_query("SELECT usid, firstname, lastname, email, avatar_url FROM `users` WHERE usid=".$userid);
        while(($row = mysqli_fetch_assoc($dbres)) != NULL) {
            $res[] = $row;
        }
        $msg = "ok";
    } else if ($action == "restart_fapi") {
        if ($_SERVER["REQUEST_METHOD"] !== "POST") {
            $msg = "error";
            $res = "Method not allowed";
        } else {
            $output = [];
            $status = 0;
            exec("sudo -n /usr/local/sbin/restart-fapi 2>&1", $output, $status);

            if ($status === 0) {
                $msg = "ok";
                $res = "FastAPI service restarted";
            } else {
                $msg = "error";
                $details = trim(implode("\n", $output));
                if ($details === "") {
                    $details = "Restart command failed. Configure sudoers for www-data on /usr/local/sbin/restart-fapi.";
                }
                $res = $details;
            }
        }
    }else if ($action == "update_password") {
        if ($_SERVER["REQUEST_METHOD"] !== "POST") {
            $msg = "error";
            $res = "Method not allowed";
        } else {
            $new_password = isset($_POST["new_password"]) ? trim($_POST["new_password"]) : "";

            if ($new_password === "") {
                $msg = "error";
                $res = "Missing password";
            } else {
                $password_hash = password_hash($new_password, PASSWORD_DEFAULT);

                if ($password_hash === false) {
                    $msg = "error";
                    $res = "Unable to hash password";
                } else {
                    $link = connect_db();
                    $escaped_password_hash = mysqli_real_escape_string($link, $password_hash);

                    do_query("UPDATE `users` SET `pass`='".$escaped_password_hash."' WHERE `usid`=".$userid);
                    close_db($link);

                    $msg = "ok";
                    $res = "Password updated";
                }
            }
        }
    } else if ($action == "upload_avatar") {
        if ($_SERVER["REQUEST_METHOD"] !== "POST") {
            $msg = "error";
            $res = "Method not allowed";
        } elseif (!isset($_FILES['avatar']) || $_FILES['avatar']['error'] !== UPLOAD_ERR_OK) {
            $msg = "error";
            $res = "No file received (error code: " . ($_FILES['avatar']['error'] ?? 'none') . ")";
        } else {
            $file = $_FILES['avatar'];
            $finfo = finfo_open(FILEINFO_MIME_TYPE);
            $mime  = finfo_file($finfo, $file['tmp_name']);
            finfo_close($finfo);

            $allowed = ['image/jpeg' => 'jpg', 'image/png' => 'png', 'image/gif' => 'gif', 'image/webp' => 'webp'];

            if (!array_key_exists($mime, $allowed)) {
                $msg = "error";
                $res = "Invalid file type: " . $mime;
            } elseif ($file['size'] > 2 * 1024 * 1024) {
                $msg = "error";
                $res = "File too large (max 2 MB)";
            } else {
                $ext      = $allowed[$mime];
                $rel_path = "img/avatars/" . $userid . "." . $ext;
                $abs_path = "/var/www/html/" . $rel_path;

                @mkdir(dirname($abs_path), 0755, true);
                if (move_uploaded_file($file['tmp_name'], $abs_path)) {
                    $link    = connect_db();
                    $escaped = mysqli_real_escape_string($link, $rel_path);
                    mysqli_query($link, "UPDATE `users` SET `avatar_url`='" . $escaped . "' WHERE `usid`=" . $userid);
                    close_db($link);
                    $_SESSION['avatar_url'] = $rel_path;
                    // Copy avatar to git source via FastAPI
                    @file_get_contents("http://127.0.0.1:8101/stealth/agents/sync_avatar?path=" . urlencode($rel_path));
                    $msg = "ok";
                    $res = $rel_path . "?v=" . time();
                } else {
                    $msg = "error";
                    $res = "Failed to save file";
                }
            }
        }
    } else if ($action == "agent_call") {
        if ($_SERVER["REQUEST_METHOD"] !== "POST") {
            $msg = "error";
            $res = "Method not allowed";
        } else {
            $body        = json_decode(file_get_contents('php://input'), true) ?? [];
            $agent_type  = $body["agent"]   ?? "";
            $agent_payload = json_encode($body["payload"] ?? []);

            $firstname   = strtolower(trim($_SESSION['firstname'] ?? ''));
            $code_agents = ["coder", "pipeline"];
            $all_agents  = ["research", "coder", "pipeline", "data"];

            if (!in_array($agent_type, $all_agents)) {
                $msg = "error";
                $res = "Unknown agent: " . $agent_type;
            } elseif (in_array($agent_type, $code_agents) && $firstname !== "guillaume") {
                $msg = "forbidden";
                $res = "Only Guillaume can use the " . $agent_type . " agent.";
            } else {
                $ch = curl_init("http://127.0.0.1:8101/stealth/agents/" . $agent_type);
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $agent_payload);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_TIMEOUT, 600);
                $fapi_response = curl_exec($ch);
                $http_code     = curl_getinfo($ch, CURLINFO_HTTP_CODE);
                curl_close($ch);

                if ($http_code === 200) {
                    $msg = "ok";
                    $res = json_decode($fapi_response, true);
                } else {
                    $msg = "error";
                    $res = $fapi_response;
                }
            }
        }
    } else if ($action == "portal_stream") {
        if ($_SERVER["REQUEST_METHOD"] !== "POST") {
            $msg = "error"; $res = "Method not allowed";
        } else {
            $body       = json_decode(file_get_contents('php://input'), true) ?? [];
            $message    = trim($body["message"] ?? "");
            $firstname  = strtolower(trim($_SESSION['firstname'] ?? ''));
            $allow_restricted = ($firstname === "guillaume");

            if ($message === "") {
                $msg = "error"; $res = "Empty message";
            } else {
                $payload = json_encode([
                    "message"          => $message,
                    "usid"             => intval($userid),
                    "channel"          => "web",
                    "allow_restricted" => $allow_restricted,
                ]);

                header('Content-Type: text/event-stream');
                header('Cache-Control: no-cache');
                header('X-Accel-Buffering: no');
                // Flush headers immediately
                if (ob_get_level()) ob_end_flush();

                $ch = curl_init("http://127.0.0.1:8101/stealth/agents/portal/stream");
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                curl_setopt($ch, CURLOPT_TIMEOUT, 600);
                curl_setopt($ch, CURLOPT_WRITEFUNCTION, function($ch, $data) {
                    echo $data;
                    flush();
                    return strlen($data);
                });
                curl_exec($ch);
                curl_close($ch);
                exit(0);
            }
        }
    } else if ($action == "admin_search_users") {
        $dbres_role = do_query("SELECT role FROM `users` WHERE usid=" . intval($userid));
        $user_role = ($r = mysqli_fetch_assoc($dbres_role)) ? ($r['role'] ?? '') : '';
        if ($user_role !== 'admin') {
            $msg = "error"; $res = "Forbidden";
        } else {
            $term = trim($_REQUEST['q'] ?? '');
            if (strlen($term) < 1) {
                $msg = "ok"; $res = [];
            } else {
                $link = connect_db();
                $escaped = mysqli_real_escape_string($link, $term);
                close_db($link);
                $sql = "SELECT u.usid, u.firstname, u.lastname, u.email, u.avatar_url, u.allowed_dbs, u.role, "
                     . "  (SELECT 1 FROM user_products WHERE usid=u.usid AND product='epineia') AS epineia "
                     . "FROM users u WHERE "
                     . "u.firstname LIKE '%{$escaped}%' OR u.lastname LIKE '%{$escaped}%' OR u.email LIKE '%{$escaped}%' "
                     . "ORDER BY u.firstname LIMIT 20";
                $dbres = do_query($sql);
                $res = [];
                while ($row = mysqli_fetch_assoc($dbres)) { $res[] = $row; }
                $msg = "ok";
            }
        }
    } else if ($action == "admin_impersonate") {
        $dbres_role = do_query("SELECT role FROM `users` WHERE usid=" . intval($userid));
        $user_role = ($r = mysqli_fetch_assoc($dbres_role)) ? ($r['role'] ?? '') : '';
        if ($user_role !== 'admin') {
            $msg = "error"; $res = "Forbidden";
        } else {
            $target = intval($_REQUEST['target_usid'] ?? 0);
            if ($target < 1) {
                $msg = "error"; $res = "Invalid user ID";
            } else {
                $dbres = do_query("SELECT usid, firstname, lastname, email FROM `users` WHERE usid=" . $target);
                $row = mysqli_fetch_assoc($dbres);
                if (!$row) {
                    $msg = "error"; $res = "User not found";
                } else {
                    $_SESSION['admin_original_usid'] = $_SESSION['usid'];
                    $_SESSION['admin_original_email'] = $_SESSION['email'];
                    $_SESSION['admin_original_firstname'] = $_SESSION['firstname'];
                    $_SESSION['usid'] = $row['usid'];
                    $_SESSION['email'] = $row['email'];
                    $_SESSION['firstname'] = $row['firstname'];
                    $_SESSION['lastname'] = $row['lastname'];
                    $msg = "ok";
                    $res = "Now impersonating " . $row['firstname'] . " " . $row['lastname'];
                }
            }
        }
    } else if ($action == "admin_restore") {
        if (!isset($_SESSION['admin_original_usid'])) {
            $msg = "error"; $res = "Not impersonating anyone";
        } else {
            $_SESSION['usid'] = $_SESSION['admin_original_usid'];
            $_SESSION['email'] = $_SESSION['admin_original_email'];
            $_SESSION['firstname'] = $_SESSION['admin_original_firstname'];
            unset($_SESSION['admin_original_usid'], $_SESSION['admin_original_email'], $_SESSION['admin_original_firstname']);
            $msg = "ok"; $res = "Restored to original session";
        }
    } else if ($action == "admin_update_user") {
        $dbres_role = do_query("SELECT role FROM `users` WHERE usid=" . intval($userid));
        $user_role = ($r = mysqli_fetch_assoc($dbres_role)) ? ($r['role'] ?? '') : '';
        if ($user_role !== 'admin') {
            $msg = "error"; $res = "Forbidden";
        } elseif ($_SERVER["REQUEST_METHOD"] !== "POST") {
            $msg = "error"; $res = "Method not allowed";
        } else {
            $target = intval($_REQUEST['target_usid'] ?? 0);
            if ($target < 1) { $msg = "error"; $res = "Invalid user ID"; }
            else {
                // Plain user-table fields go through UPDATE; product flags go through user_products.
                $allowed = ['firstname', 'lastname', 'email'];
                $product_flags = ['epineia', 'jupyter'];
                $link = connect_db();
                $sets = [];
                foreach ($allowed as $field) {
                    if (isset($_POST[$field])) {
                        $val = mysqli_real_escape_string($link, $_POST[$field]);
                        $sets[] = "`{$field}`='{$val}'";
                    }
                }
                if (!empty($sets)) {
                    mysqli_query($link, "UPDATE `users` SET " . implode(', ', $sets) . " WHERE `usid`=" . $target);
                }
                // Toggle per-product access (1 = grant, 0 = revoke)
                $touched_flags = false;
                foreach ($product_flags as $product) {
                    if (isset($_POST[$product])) {
                        $touched_flags = true;
                        if (intval($_POST[$product]) > 0) {
                            mysqli_query($link, "INSERT IGNORE INTO user_products (usid, product, role) VALUES (" . $target . ", '" . $product . "', 'user')");
                        } else {
                            mysqli_query($link, "DELETE FROM user_products WHERE usid=" . $target . " AND product='" . $product . "'");
                        }
                    }
                }
                close_db($link);
                if (empty($sets) && !$touched_flags) { $msg = "error"; $res = "No fields to update"; }
                else { $msg = "ok"; $res = "User updated"; }
            }
        }
    } else if ($action == "telegram_get_token") {
        $token = strtoupper(substr(bin2hex(random_bytes(4)), 0, 6));
        do_query("UPDATE `users` SET `telegram_link_token`='".$token."' WHERE `usid`=".$userid);
        $msg = "ok";
        $res = $token;
    } else {
        $msg = "error";
        $res = "Unknown action specified";
    }

    header("Content-Type: text/json");
    print(json_encode(Array("msg" => $msg, "res" => $res)));
    exit(0);
}
?>