<?php
// admin_actions.php (Ya jo bhi aapki file ka naam hai)
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
// Config path sahi kar lena
require_once __DIR__ . "/includes/config.php"; 

if (!isset($_SESSION['admin_id'])) exit("Access Denied");

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

/* ======================
   1. SEARCH USER
====================== */
if ($action === "search") {

    $mobile = $_POST['mobile'];

    $q = $conn->prepare("SELECT * FROM users WHERE mobile=?");
    $q->bind_param("s", $mobile);
    $q->execute();
    $r = $q->get_result();

    if ($r->num_rows == 0) {
        echo "<p style='color:red; font-weight:bold;'>❌ User not found</p>";
        exit;
    }

    $u = $r->fetch_assoc();
    $status = $u['status'] == 'blocked' ? '<span style="color:red">Blocked</span>' : '<span style="color:green">Active</span>';
    
    // Balance check (Adjust fields based on your DB)
    $bal = $u['income_balance'] ?? $u['balance'] ?? 0;

    echo "
    <div style='background:#f9f9f9; padding:15px; border-radius:10px; border:1px solid #ddd;'>
        <b>User ID:</b> {$u['id']}<br>
        <b>Mobile:</b> {$u['mobile']}<br>
        <b>Status:</b> {$status}<br>
        <b>Balance:</b> ₹{$bal}<br><br>

        <b>Bank Name:</b> ".($u['bank_name'] ?? 'Not Set')."<br>
        <b>Account No:</b> ".($u['account_number'] ?? 'Not Set')."<br>
        <b>IFSC:</b> ".($u['ifsc'] ?? 'Not Set')."<br><br>

        <div class='flex' style='display:flex; gap:10px;'>
            <button class='btn-red' style='background:red; color:white; padding:5px 10px; border:none; cursor:pointer;' onclick='deleteBank({$u['id']})'>Delete Bank</button>
            
            <button class='btn-gray' style='background:gray; color:white; padding:5px 10px; border:none; cursor:pointer;' onclick='toggleBlock({$u['id']})'>
                ".($u['status']=="blocked"?"Unblock User":"Block User")."
            </button>
            
            <button class='btn-green' style='background:green; color:white; padding:5px 10px; border:none; cursor:pointer;' onclick='loginAsUser({$u['id']})'>Login As User</button>
        </div>
    </div>
    ";
    exit;
}

/* ======================
   2. DELETE BANK
====================== */
if ($action === "delete_bank") {
    $id = (int)$_POST['user_id'];
    $stmt = $conn->prepare("UPDATE users SET bank_name = NULL, account_number = NULL, ifsc = NULL WHERE id = ?");
    $stmt->bind_param("i", $id);
    
    if ($stmt->execute()) { echo "Bank details deleted successfully"; } 
    else { echo "Failed to delete bank details"; }
    exit;
}

/* ======================
   3. BLOCK / UNBLOCK
====================== */
if ($action === "toggle_block") {
    $id = (int)$_POST['user_id'];
    
    $q = $conn->prepare("SELECT status FROM users WHERE id=?");
    $q->bind_param("i", $id);
    $q->execute();
    $u = $q->get_result()->fetch_assoc();

    $new = ($u['status'] === 'blocked') ? 'active' : 'blocked';

    $stmt = $conn->prepare("UPDATE users SET status=? WHERE id=?");
    $stmt->bind_param("si", $new, $id);
    $stmt->execute();

    echo "User status updated to " . ucfirst($new);
    exit;
}

/* ======================
   4. LOGIN AS USER (FIXED PART)
====================== */
if ($action === "login_as_user") {

    $user_id = (int)$_POST['user_id'];

    // Token Generate
    $token = bin2hex(random_bytes(32));
    $expiry = date("Y-m-d H:i:s", time() + 600); // 10 Min Valid

    // Delete Old Tokens
    $conn->query("DELETE FROM admin_login_tokens WHERE user_id=$user_id");

    // Insert New Token
    $stmt = $conn->prepare("INSERT INTO admin_login_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
    $stmt->bind_param("iss", $user_id, $token, $expiry);
    
    if($stmt->execute()){
        // ✅ Correct URL (https:// and user_login_handler.php)
        echo "https://jkm70x.long-term-application.com/user_login_handler.php?token=" . $token;
    } else {
        echo "error";
    }
    exit;
}
?>