<?php
include_once '../config/connect.php';
session_start();

if (!isset($_SESSION['agent_level']) || $_SESSION['agent_level'] !== 'admin') {
    header('Location: ../index?page=ManagementAgent&alert=access_denied');
    exit();
}

if (!isset($_POST['delete_agent'])) {
    header('Location: ../index?page=ManagementAgent&alert=invalid_request');
    exit();
}

$agentIdentifier = trim((string)($_POST['agent_identifier'] ?? ''));
$targetAgent = agent_find_by_identifier($call, $agentIdentifier);

if ($targetAgent === null) {
    header('Location: ../index?page=ManagementAgent&alert=delete_failed');
    exit();
}

$targetAgentName = agent_public_name($targetAgent);
$targetAgentNameSql = mysqli_real_escape_string($call, $targetAgentName);
$targetUplineWhere = agent_reference_condition($call, 'agent_upline', $targetAgent);
$currentAgentRefs = agent_identity_values((array)($_SESSION['admin'] ?? []));

// ❌ Admin tidak boleh hapus dirinya sendiri
if (in_array($targetAgentName, $currentAgentRefs, true) || in_array((string)($targetAgent['agent_code'] ?? ''), $currentAgentRefs, true)) {
    header('Location: ../index?page=ManagementAgent&alert=self_delete');
    exit();
}

// ❌ Cek apakah agent punya downline
$cek_downline = mysqli_query(
    $call,
    "SELECT id FROM tb_agent WHERE $targetUplineWhere LIMIT 1"
);

if (mysqli_num_rows($cek_downline) > 0) {
    header('Location: ../index?page=ManagementAgent&alert=has_downline');
    exit();
}

// ✅ Delete agent
$delete = mysqli_query(
    $call,
    "DELETE FROM tb_agent WHERE agent_name = '$targetAgentNameSql'"
);

if ($delete) {
    header('Location: ../index?page=ManagementAgent&alert=delete_success');
} else {
    header('Location: ../index?page=ManagementAgent&alert=delete_failed');
}
exit();
