<?php
// approve_admin_login.php
session_start();
require_once 'auth/db.php';
header('Content-Type: application/json');

// must be an already logged in admin (approver)
if (!isset($_SESSION['is_admin']) || $_SESSION['is_admin'] !== true) {
    echo json_encode(['success'=>false, 'message'=>'Unauthorized']);
    exit;
}

$approverId = intval($_SESSION['user_id']);
$data = json_decode(file_get_contents('php://input'), true);
$pendingId = intval($data['pending_id'] ?? 0);
$action = ($data['action'] ?? 'approve') === 'approve' ? 'approve' : 'deny';

if (!$pendingId) { echo json_encode(['success'=>false,'message'=>'Missing id']); exit; }

// load request
$stmt = $conn->prepare("SELECT admin_user_id, status FROM pending_admin_logins WHERE id = ?");
$stmt->bind_param("i",$pendingId);
$stmt->execute();
$stmt->bind_result($requestingAdminId, $curStatus);
if (!$stmt->fetch()) {
    echo json_encode(['success'=>false,'message'=>'Not found']); exit;
}
$stmt->close();

if ($curStatus !== 'pending') {
    echo json_encode(['success'=>false,'message'=>'Already processed']); exit;
}

if ($requestingAdminId == $approverId) {
    echo json_encode(['success'=>false,'message'=>'You cannot approve your own request']); exit;
}

if ($action === 'approve') {
    $token = bin2hex(random_bytes(24));
    $stmt = $conn->prepare("UPDATE pending_admin_logins SET status='approved', approved_by=?, approved_at=NOW(), approved_token=? WHERE id=?");
    $stmt->bind_param("isi", $approverId, $token, $pendingId);
    $stmt->execute();
    $stmt->close();

    // (Optional) send a notification/email or log the approval

    echo json_encode(['success'=>true, 'token'=>$token]);
} else {
    $stmt = $conn->prepare("UPDATE pending_admin_logins SET status='denied', approved_by=?, approved_at=NOW() WHERE id=?");
    $stmt->bind_param("ii", $approverId, $pendingId);
    $stmt->execute();
    $stmt->close();
    echo json_encode(['success'=>true, 'message'=>'Denied']);
}