<?php
/* ============================================================================
   WBMCZ — Admin · Switch mode (view the site as a member)

   An admin opens a member's own dashboard, sees exactly what that member sees,
   and can work inside it. A gold bar sits at the top of every page the whole
   time saying whose account is open, with one button to come back.

   How it stays safe:
     · only an admin holding "Manage Customers" may start a switch
     · nobody can switch into another admin or staff account
     · the real admin id is kept in $_SESSION['switch_admin'] and is never
       thrown away, so "Return to admin" always works
     · starting and ending a switch is written to the member's update history,
       so there is a permanent record of who looked at what
   ============================================================================ */

require_once __DIR__ . '/../config.php';
require_once __DIR__ . '/../db.php';
require_once __DIR__ . '/../includes/functions.php';

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

/* ---------------------------------------------------------------------------
   COME BACK — this has to work even while the session says "customer",
   which is why it is checked before any admin guard.
   --------------------------------------------------------------------------- */
if (isset($_GET['back'])) {
    if (empty($_SESSION['switch_admin']['id'])) { redirect('login.php'); }

    $admin = $_SESSION['switch_admin'];
    $was   = (int)($_SESSION['user_id'] ?? 0);

    /* close the note in the member's history */
    try {
        $db->insert("INSERT INTO user_update_history (user_id, field_label, old_value, new_value, updated_by, updated_by_name)
                     VALUES (?, 'Switch mode', 'Open', 'Closed', ?, ?)",
                    [$was, $admin['id'], $admin['name']]);
    } catch (\Throwable $e) {}

    $_SESSION['user_id']     = $admin['id'];
    $_SESSION['user_name']   = $admin['name'];
    $_SESSION['user_mobile'] = $admin['mobile'];
    $_SESSION['user_type']   = $admin['type'];
    unset($_SESSION['switch_admin']);

    $_SESSION['flash_success'] = 'You are back on your own admin account.';
    redirect('user_list.php');
}

/* ---------------------------------------------------------------------------
   START — from here on this is an admin-only screen
   --------------------------------------------------------------------------- */
if (!isLoggedIn() || !isAdmin()) { redirect('login.php'); }
if (!hasPermission('manage_users')) { die('Access Denied: you do not have permission to open a member account.'); }

/* already inside somebody else's account? come back first */
if (!empty($_SESSION['switch_admin']['id'])) {
    $_SESSION['flash_error'] = 'You are already in switch mode. Return to your admin account first.';
    redirect('user_list.php');
}

$target = (int)($_GET['uid'] ?? 0);
if ($target <= 0) { redirect('user_list.php'); }

$row = $db->select("SELECT id, name, mobile, user_type, status, deleted_at FROM users WHERE id = ?", [$target]);
if (empty($row)) {
    $_SESSION['flash_error'] = 'That member no longer exists.';
    redirect('user_list.php');
}
$u = $row[0];

/* ---- the rules ---- */
if (!empty($u['deleted_at'])) {
    $_SESSION['flash_error'] = 'That account is deleted. Restore it first.';
    redirect('user_list.php');
}
if ((string)$u['user_type'] === 'admin') {
    $_SESSION['flash_error'] = 'Switch mode is for members and sellers only — you cannot open another staff account.';
    redirect('user_list.php');
}
if ((int)$u['id'] === (int)$_SESSION['user_id']) {
    redirect('user_list.php');
}

/* remember who we really are */
$me = $db->select("SELECT id, name, mobile, user_type FROM users WHERE id = ?", [(int)$_SESSION['user_id']]);
$me = !empty($me) ? $me[0] : null;
if (!$me) { redirect('login.php'); }

$_SESSION['switch_admin'] = [
    'id'     => (int)$me['id'],
    'name'   => (string)$me['name'],
    'mobile' => (string)$me['mobile'],
    'type'   => (string)$me['user_type'],
    'since'  => date('Y-m-d H:i:s'),
];

/* leave a trail on the member's record */
try {
    $db->insert("INSERT INTO user_update_history (user_id, field_label, old_value, new_value, updated_by, updated_by_name)
                 VALUES (?, 'Switch mode', 'Closed', ?, ?, ?)",
                [(int)$u['id'], 'Opened by ' . $me['name'], (int)$me['id'], (string)$me['name']]);
} catch (\Throwable $e) {}

/* become the member */
$_SESSION['user_id']     = (int)$u['id'];
$_SESSION['user_name']   = (string)$u['name'];
$_SESSION['user_mobile'] = (string)$u['mobile'];
$_SESSION['user_type']   = (string)$u['user_type'];

redirect(((string)$u['user_type'] === 'seller') ? '../seller/index.php' : '../dashboard.php');
