<?php
require_once __DIR__ . '/config.php';
session_start();

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

// Auth check
function check_auth() {
    if (empty($_SESSION['logged_in'])) {
        http_response_code(401);
        echo json_encode(['ok' => false, 'error' => 'Not authenticated']);
        exit;
    }
}

function get_db() {
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($conn->connect_error) {
        http_response_code(500);
        echo json_encode(['ok' => false, 'error' => 'DB connection failed']);
        exit;
    }
    $conn->set_charset('utf8mb4');
    return $conn;
}

function vps_request($path, $method = 'GET', $body = null) {
    $url = VPS_API_URL . $path;
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'X-Auth-Token: ' . VPS_API_TOKEN,
        'Content-Type: application/json',
    ]);
    if ($method === 'POST') {
        curl_setopt($ch, CURLOPT_POST, true);
        if ($body !== null) {
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
        }
    }
    $response = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);
    if ($err) {
        return ['ok' => false, 'error' => "VPS unreachable: $err"];
    }
    return json_decode($response, true) ?: ['ok' => false, 'error' => 'Invalid VPS response'];
}

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

// --- Login ---
if ($action === 'login') {
    $input = json_decode(file_get_contents('php://input'), true);
    $user = $input['username'] ?? '';
    $pass = $input['password'] ?? '';
    if ($user === DASHBOARD_USER && $pass === DASHBOARD_PASS) {
        $_SESSION['logged_in'] = true;
        echo json_encode(['ok' => true]);
    } else {
        echo json_encode(['ok' => false, 'error' => 'Invalid credentials']);
    }
    exit;
}

if ($action === 'logout') {
    session_destroy();
    echo json_encode(['ok' => true]);
    exit;
}

if ($action === 'check_auth') {
    echo json_encode(['ok' => !empty($_SESSION['logged_in'])]);
    exit;
}

// All other actions require auth
check_auth();

// --- Stats ---
if ($action === 'stats') {
    $db = get_db();
    $total = $db->query("SELECT COUNT(*) as c FROM table_tg_sessions")->fetch_assoc()['c'];
    $pending = $db->query("SELECT COUNT(*) as c FROM table_tg_sessions WHERE has_left_channels = 0")->fetch_assoc()['c'];
    $cleaned = $db->query("SELECT COUNT(*) as c FROM table_tg_sessions WHERE has_left_channels = 1")->fetch_assoc()['c'];
    $failed = $db->query("SELECT COUNT(*) as c FROM table_tg_sessions WHERE has_left_channels = -1")->fetch_assoc()['c'];
    $db->close();
    echo json_encode([
        'ok' => true,
        'total' => (int)$total,
        'pending' => (int)$pending,
        'cleaned' => (int)$cleaned,
        'failed' => (int)$failed,
    ]);
    exit;
}

// --- Sessions list ---
if ($action === 'sessions') {
    $db = get_db();
    $filter = $_GET['filter'] ?? 'all';
    $where = '';
    if ($filter === 'pending') $where = 'WHERE has_left_channels = 0';
    elseif ($filter === 'cleaned') $where = 'WHERE has_left_channels = 1';
    elseif ($filter === 'failed') $where = 'WHERE has_left_channels = -1';

    $result = $db->query("SELECT id, phone_number, channels_joined, has_left_channels, created_at, updated_at FROM table_tg_sessions $where ORDER BY id DESC");
    $rows = [];
    while ($row = $result->fetch_assoc()) {
        $rows[] = $row;
    }
    $db->close();
    echo json_encode(['ok' => true, 'sessions' => $rows]);
    exit;
}

// --- Delete session ---
if ($action === 'delete') {
    $input = json_decode(file_get_contents('php://input'), true);
    $id = (int)($input['id'] ?? 0);
    if (!$id) {
        echo json_encode(['ok' => false, 'error' => 'No ID']);
        exit;
    }
    $db = get_db();
    $stmt = $db->prepare("DELETE FROM table_tg_sessions WHERE id = ?");
    $stmt->bind_param('i', $id);
    $stmt->execute();
    $db->close();
    echo json_encode(['ok' => true]);
    exit;
}

// --- Run all pending ---
if ($action === 'run_all') {
    echo json_encode(vps_request('/run_all', 'POST'));
    exit;
}

// --- Run selected ---
if ($action === 'run_selected') {
    $input = json_decode(file_get_contents('php://input'), true);
    $ids = $input['ids'] ?? [];
    echo json_encode(vps_request('/run_selected', 'POST', ['ids' => $ids]));
    exit;
}

// --- Cleanup status ---
if ($action === 'run_status') {
    echo json_encode(vps_request('/status'));
    exit;
}

echo json_encode(['ok' => false, 'error' => 'Unknown action']);
