<?php
ob_start();
session_start();

/*****************************************************************************
// PROGRAM DESCRIPTION :  PROGRAM FOR ADMIN LOGIN VALIDATION
//*****************************************************************************/

include_once '../includes/session.php';
include '../includes/constants.php';
include '../includes/functions.php';
include_once '../includes/allstripslashes.php';

$partners = new partners();
$partners->connection($host, $user, $pass, $db);

/********************* Variables ********************************************/
$login  = trim($_POST['login'] ?? '');
$passwd = trim($_POST['passwd'] ?? '');
/***************************************************************************/

// Validate login input
if (preg_match('/\s/', $login) || preg_match('/\s/', $passwd)) {
    header("Location: index.php?Err=ad1002");
    exit;
}

// Escape login string for query
$loginEscaped = mysqli_real_escape_string($partners->conn, $login);

// Fetch admin user data
$sql = "SELECT * FROM partners_adminusers WHERE adminusers_login = '$loginEscaped' LIMIT 1";
$result = mysqli_query($partners->conn, $sql);

if ($result && mysqli_num_rows($result) > 0) {
    $row = mysqli_fetch_assoc($result);

    // Verify password using password_verify
    if (password_verify($passwd, $row['adminusers_password'])) {
        $adminUserId = (int)$row['adminusers_id'];

        // Get last login IP and time diff
        $ipQuery = "
            SELECT adminusers_ip, UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(adminusers_lastLogin)
            FROM partners_adminusers
            WHERE adminusers_id = $adminUserId
        ";
        $ret1 = mysqli_query($partners->conn, $ipQuery);
        list($ip, $timeDiff) = mysqli_fetch_row($ret1);
        $_SESSION['ADMINLASTLOGGEDIP'] = $ip;

        // Set session variables
        $_SESSION['ADMINUSERID'] = stripslashes($row['adminusers_id']);
        $_SESSION['ADMIN']       = stripslashes($row['adminusers_login']);
        $_SESSION['MAIL']        = stripslashes($row['adminusers_email']);

        // Redirect based on admin ID
        if ($_SESSION['ADMINUSERID'] == '1') {
            header("Location: index.php?Act=merchants&status=all");
        } else {
            header("Location: index.php?Act=welcome");
        }
        exit;
    }
}

// Invalid login
header("Location: index.php?Err=ad1001");
exit;
?>
