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

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['profileEdit'])) {
    // Validate and sanitize inputs
    $agent_identifier = trim((string)($_POST['agent_identifier'] ?? ($_POST['agent_name'] ?? '')));
    $agent_ip1 = isset($_POST['agent_IP1']) ? mysqli_real_escape_string($call, $_POST['agent_IP1']) : '';
    $agent_whatsapp_raw = isset($_POST['agent_whatsapp']) ? (string)$_POST['agent_whatsapp'] : '';
    $agent_whatsapp = wa_normalize_number($agent_whatsapp_raw);
    $password = isset($_POST['agent_password']) ? $_POST['agent_password'] : '';
    $current_agent_level = trim((string)($_SESSION['admin']['agent_level'] ?? ($_SESSION['agent_level'] ?? '')));

    // Validate IP address
    if (!filter_var($agent_ip1, FILTER_VALIDATE_IP)) {
        header('Location: ../index?page=Profile&msg=30');
        exit();
    }

    if ($agent_whatsapp_raw !== '' && $agent_whatsapp === '') {
        header('Location: ../index?page=Profile&msg=50');
        exit();
    }

    // Check if agent exists
    $agent = agent_find_by_identifier($call, $agent_identifier);

    if ($agent === null) {
        header('Location: ../index?page=Profile&msg=8');
        exit();
    }

    $agent_name = agent_public_name($agent);
    $agent_name_sql = mysqli_real_escape_string($call, $agent_name);

    $password_changed = false;
    $query = '';

    try {
        if (!empty($password)) {
            // Using md5 for backward compatibility (though not recommended for new projects)
            $hashed_password = md5($password);
            $query = "UPDATE tb_agent SET 
                     agent_IP1 = '$agent_ip1', 
                     agent_IP2 = '$agent_ip1', 
                     agent_password = '$hashed_password', 
                     original_password = '$password' 
                     WHERE agent_name = '$agent_name_sql'";
            $password_changed = true;
        } else {
            $query = "UPDATE tb_agent SET 
                     agent_IP1 = '$agent_ip1', 
                     agent_IP2 = '$agent_ip1' 
                     WHERE agent_name = '$agent_name_sql'";
        }

        // Execute the query
        if ($call->query($query)) {
            if (!wa_save_agent_whatsapp($call, $agent_name, $agent_whatsapp)) {
                throw new Exception('WhatsApp update failed');
            }

            if ($password_changed) {
                // Clear all session variables
                $_SESSION = array();
                // Destroy the session
                session_destroy();
                header('Location: ../login.php?msg=logout');
            } else {
                if ($current_agent_level !== 'admin' && wa_agent_requires_verification($call, $agent_name)) {
                    header('Location: ../index?page=VerifyWhatsapp&msg=66');
                } else {
                    header('Location: ../index?page=Profile&msg=15');
                }
            }
            exit();
        } else {
            throw new Exception('Database update failed');
        }
    } catch (Exception $e) {
        header('Location: ../index?page=Profile&msg=13');
        exit();
    }
} else {
    // Invalid request method
    header('Location: ../index?page=Profile');
    exit();
}
?>
