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

$data = json_decode(file_get_contents('php://input'), true);
$pendingId = intval($data['pending_id'] ?? 0);
$token = $data['token'] ?? '';

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

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

if ($status !== 'approved' || !$approved_token || !hash_equals($approved_token, $token)) {
    echo json_encode(['success'=>false,'message'=>'Not approved or invalid token']); exit;
}

// Everything ok — set admin session
$_SESSION['user_id'] = intval($adminUserId);
$_SESSION['is_admin'] = true;

// optionally mark the pending row as used (or keep for audit)
$stmt = $conn->prepare("UPDATE pending_admin_logins SET status='approved', approved_at=NOW() WHERE id = ?");
$stmt->bind_param("i", $pendingId);
$stmt->execute();
$stmt->close();

echo json_encode(['success'=>true]);
