<?php
include_once '../config/connect.php';
require_once '../config/whatsapp.php';
error_reporting(E_ALL);

ini_set('display_errors', 1);

if (isset($_POST['masuk'])) {
    $userid = mysqli_real_escape_string($call, $_POST['userid']);
    $password = md5($_POST['password']);

    if (empty($userid) || empty($password)) {
        header('Location: ../login?msg=5');
        exit();
    } else {
        $cek_config_akun = mysqli_query($call, "SELECT * FROM tb_agent WHERE agent_name = '$userid'");
        $data_config_akun = mysqli_fetch_array($cek_config_akun);

        if ($data_config_akun) {
            if ($data_config_akun['agent_status'] == "blocked") {
                header('Location: ../login?msg=6');
                exit();
            } else if ($password != $data_config_akun['agent_password']) {
                header('Location: ../login?msg=7');
                exit();
            } else {
                // Login berhasil
                $_SESSION['admin'] = $data_config_akun;
                $_SESSION['agent_level'] = $data_config_akun['agent_level'];
                $requiresWhatsappVerification = false;

                if (($data_config_akun['agent_level'] ?? '') !== 'admin') {
                    $agentName = trim((string)($data_config_akun['agent_name'] ?? '-'));
                    $agentLevel = trim((string)($data_config_akun['agent_level'] ?? '-'));
                    $loginTime = date('Y-m-d H:i:s');
                    $loginTimeLabel = date('d/m/Y H:i') . ' WIB';
                    $ipAddress = $_SERVER['REMOTE_ADDR'] ?? 'unknown';

                    $message = "🔐 NOXPAY API - Notifikasi Login Agent\n\n"
                        . "Status: ✅ Berhasil\n"
                        . "Agent: {$agentName}\n"
                        . "Level: {$agentLevel}\n"
                        . "IP: {$ipAddress}\n"
                        . "Waktu: {$loginTimeLabel}\n\n"
                        . "✅ Aktivitas login agent berhasil terdeteksi.";

                    wa_send_admin_alert($call, $message);

                    $agentWhatsapp = wa_get_verified_agent_whatsapp($call, $agentName);
                    if ($agentWhatsapp === '') {
                        $agentWhatsapp = wa_get_agent_whatsapp($call, $agentName);
                    }

                    if ($agentWhatsapp !== '') {
                        $agentMessage = "🔐 NOXPAY API - Notifikasi Login\n\n"
                            . "Status: ✅ Berhasil\n"
                            . "Agent: {$agentName}\n"
                            . "IP: {$ipAddress}\n"
                            . "Waktu: {$loginTimeLabel}\n\n"
                            . "✅ Login berhasil ke akun Anda.";

                        $agentNotificationSent = wa_send_message($call, $agentWhatsapp, $agentMessage);
                        wa_log($agentNotificationSent ? 'agent_login_notification_sent' : 'agent_login_notification_failed', [
                            'agent_name' => $agentName,
                            'whatsapp' => $agentWhatsapp,
                            'ip' => $ipAddress,
                        ]);
                    } else {
                        wa_log('agent_login_notification_skipped', [
                            'agent_name' => $agentName,
                            'reason' => 'no_whatsapp',
                            'ip' => $ipAddress,
                        ]);
                    }

                    $requiresWhatsappVerification = wa_agent_requires_verification($call, $agentName);
                }

                if ($requiresWhatsappVerification) {
                    header('Location: ../VerifyWhatsapp?msg=68');
                    exit();
                }

                header('Location: ../?msg=3');
                exit();
            }
        } else {
            header('Location: ../login?msg=8');
            exit();
        }
    }
}
?>
