<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

include 'vendor/autoload.php'; // Include the PHPMailer library

/**
 * Format currency amount based on system settings
 */
function formatCurrency($amount, $precision = 2) {
    static $currencySettings = null;
    
    // Load currency settings only once
    if ($currencySettings === null) {
        try {
            if (file_exists('config.php')) {
                include_once 'config.php';
                
                $dsn = "mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE . ";charset=utf8mb4";
                $pdo = new PDO($dsn, MYSQL_USER, MYSQL_PASSWORD, [
                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                ]);
                
                $stmt = $pdo->prepare("
                    SELECT setting_name, setting_value 
                    FROM settings 
                    WHERE setting_name IN ('currency_symbol', 'currency_position')
                ");
                $stmt->execute();
                $results = $stmt->fetchAll();
                
                $currencySettings = [
                    'currency_symbol' => '$',
                    'currency_position' => 'before'
                ];
                
                foreach ($results as $row) {
                    $currencySettings[$row['setting_name']] = $row['setting_value'];
                }
            } else {
                $currencySettings = [
                    'currency_symbol' => '$',
                    'currency_position' => 'before'
                ];
            }
        } catch (Exception $e) {
            $currencySettings = [
                'currency_symbol' => '$',
                'currency_position' => 'before'
            ];
        }
    }
    
    $formattedAmount = number_format($amount, $precision);
    
    if ($currencySettings['currency_position'] === 'before') {
        return $currencySettings['currency_symbol'] . $formattedAmount;
    } else {
        return $formattedAmount . $currencySettings['currency_symbol'];
    }
}

/**
 * Get currency symbol only
 */
function getCurrencySymbol() {
    static $symbol = null;
    
    if ($symbol === null) {
        try {
            if (file_exists('config.php')) {
                include_once 'config.php';
                
                $dsn = "mysql:host=" . MYSQL_HOST . ";dbname=" . MYSQL_DATABASE . ";charset=utf8mb4";
                $pdo = new PDO($dsn, MYSQL_USER, MYSQL_PASSWORD);
                
                $stmt = $pdo->prepare("SELECT setting_value FROM settings WHERE setting_name = 'currency_symbol'");
                $stmt->execute();
                $result = $stmt->fetch();
                
                $symbol = $result ? $result['setting_value'] : '$';
            } else {
                $symbol = '$';
            }
        } catch (Exception $e) {
            $symbol = '$';
        }
    }
    
    return $symbol;
}
// Function to send notifications to Telegram
function send_telegram_notification($message, $bot_token, $chat_id)
{

  $telegram_url = "https://api.telegram.org/bot$bot_token/sendMessage?chat_id=$chat_id&text=" . urlencode($message);
  // Make the request to Telegram API
  $ch = curl_init();  
  curl_setopt($ch, CURLOPT_URL, $telegram_url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  $response = curl_exec($ch);
  curl_close($ch);

  return $response;
}


// Helper functions for notifications
function formatPhoneNumber($phone) {
  $phone = preg_replace('/[^0-9]/', '', $phone);
  if (preg_match('/^0/', $phone)) {
      $phone = preg_replace('/^0/', '254', $phone);
  } elseif (preg_match('/^7/', $phone)) {
      $phone = '254' . $phone;
  }
  return $phone;
}

function sendWhatsAppNotification($phone, $message) {
  $whatsapp_url = "https://admin.netxtreme.top/?_route=plugin/whatsappGateway_send" .
                 "&to=$phone" .
                 "&msg=$message" .
                 "&secret=91bc70bf6d62f1216fc5e4e4903698c8";
  
  $result = @file_get_contents($whatsapp_url);
  error_log("WhatsApp to $phone. Response: " . ($result ?: 'No response'));
  return $result;
}


// Example of how you could notify the admin when a new client registers
function notify_new_client($conn, $username, $email, $password, $phone, $subdomain, $bot_token, $chat_id, $main_domain)
{
  $domain = "https://$subdomain.$main_domain"; // Format the domain using the subdomain

  $message = "==========================\n";
  $message .= "     NEW CLIENT REGISTRATION\n";
  $message .= "==========================\n";
  $message .= "Username : $username\n";
  $message .= "Phone    : $phone\n";
  $message .= "Domain   : $domain/admin\n";
  $message .= "==========================\n";
  $message .= "     ACCOUNT LOGIN DETAILS\n";
  $message .= "==========================\n";
  $message .= "Username : admin\n";
  $message .= "Password : admin\n";
  $message .= "==========================\n";
  $message .= "Please verify the details and proceed with activation.\n";
  $message .= "==========================";

  // Send the notification to Telegram
  send_telegram_notification($message, $bot_token, $chat_id);

  //SEND EMAIL TO CLIENT

  $email_message = '
  <!DOCTYPE html>
  <html>
  <head>
      <style>
          body {
              font-family: Arial, sans-serif;
              background-color: #f4f4f4;
              padding: 20px;
          }
          .email-container {
              background: #ffffff;
              padding: 20px;
              border-radius: 8px;
              box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
              max-width: 600px;
              margin: auto;
          }
          .email-header {
              text-align: center;
              font-size: 20px;
              font-weight: bold;
              color: #333;
          }
          .email-body {
              margin-top: 20px;
              font-size: 16px;
              color: #555;
              line-height: 1.6;
          }
          .account-details {
              background: #f8f9fa;
              padding: 10px;
              border-radius: 5px;
              margin: 15px 0;
          }
          .footer {
              font-size: 14px;
              color: #777;
              text-align: center;
              margin-top: 20px;
          }
      </style>
  </head>
  <body>
      <div class="email-container">
          <div class="email-header">
              Welcome to ' . COMPANY_NAME . '
          </div>
          <div class="email-body">
              <p>Dear ' . $username . ',</p>
              <p>Thank you for registering with <strong>' . COMPANY_NAME . '</strong>.</p>
              <p>Your account has been created successfully.</p>
              <div class="account-details">
                  <strong>ACCOUNT LOGIN DETAILS</strong><br>
                  <strong>Username:</strong> admin<br>
                  <strong>Password:</strong> admin
              </div>
              <p>Please verify the details and proceed with activation.</p>
              <p>If you have any questions, feel free to contact us.</p>
          </div>
          <div class="footer">
              Best regards,<br>
              <strong>' . COMPANY_NAME . ' Team</strong><br>
              <em>This is an automated message, please do not reply.</em>
          </div>
      </div>
  </body>
  </html>
  ';

  $subject = "Welcome to " . COMPANY_NAME . " - Account Created Successfully";

  // Send the email to the client
  sendEmail($conn, $email, $subject, $email_message);


  //SEND SMS TO CLIENT
  $sms_message = "Dear $username, welcome to " . COMPANY_NAME . ". Login: admin/admin. Verify & activate. Need help? Contact us.";
  $setting_name = 'sms_api_url'; // Define the setting name for SMS API URL
  //GET APP SMS API URL FROM DATABASE
  $stmt = $conn->prepare("SELECT setting_value FROM settings WHERE setting_name = ?");
  $stmt->bind_param("s", $setting_name);
  $stmt->execute();
  $setting_value = null; // Declare the variable before binding
  $stmt->bind_result($setting_value);
  $stmt->fetch();
  $stmt->close();
  $api_url = $setting_value; // Get the API URL from the database

  sendSMS($api_url, $phone, $sms_message);

}


function generateLicenseKey($length = 8)
{
  $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  $licenseKey = 'ISP-';
  for ($i = 0; $i < $length; $i++) {
    $licenseKey .= $characters[rand(0, strlen($characters) - 1)];
  }
  return $licenseKey;
}

function createUserAndLicense($isp_name, $email, $username, $subdomain, $duration, $phone, $main_domain, $servername, $dbusername, $dbpassword, $dbname)
{

  // Establish database connection
  $conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }

  // Generate license key
  $licenseKey = generateLicenseKey();
  $expiryDate = date('Y-m-d', strtotime("+" . intval($duration) . " days"));
  $basePath = "/var/www/html/";
  $userPath = $basePath . $username;
  $domain = "https://" . trim($subdomain, ".") . "." . ltrim($main_domain, ".");
  // Insert user into database
  $stmt = $conn->prepare("INSERT INTO users (username, email, folder_path,  subdomain, domain, phone) VALUES (?, ?, ?, ?, ?, ?)");
  $stmt->bind_param("ssssss", $username, $email, $userPath, $subdomain, $domain, $phone);
  if (!$stmt->execute()) {
    echo "<script>window.location.href = 'index.php?error='Failed to insert user into database: ' . $stmt->error;</script>";
  }


  $userId = $conn->insert_id;
  // Insert license into database with status = 'active'
  $stmt = $conn->prepare("INSERT INTO licenses (user_id, license_key, expiry_date, status) VALUES (?, ?, ?, 'active')");
  $stmt->bind_param("iss", $userId, $licenseKey, $expiryDate);
  if (!$stmt->execute()) {
    echo "<script>window.location.href = 'index.php?error=" . urlencode('Failed to insert license into database: ' . $stmt->error) . "';</script>";
  }

  $stmt->close();

  // Store license in a file inside the user's folder
  $licenseFilePath = $userPath . "/license.txt";
  if (file_put_contents($licenseFilePath, "License Key: $licenseKey\nExpiry Date: $expiryDate") === false) {
    echo "<script>window.location.href = 'index.php?error='Failed to store license in file: ' . $licenseFilePath;</script>";
  }

  $conn->close();
}

function checkUserLicensesExpired($servername, $dbusername, $dbpassword, $dbname, $bot_token, $chat_id)
{
  // Establish database connection
  $conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }
  // Get all licenses
  $licenses = $conn->query("SELECT * FROM licenses WHERE status = 'active'");
  if ($licenses->num_rows > 0) {
    while ($license = $licenses->fetch_assoc()) {
      $expiryDate = strtotime($license['expiry_date']);
      $today = strtotime(date('Y-m-d'));
      if ($today > $expiryDate) {
        // License has expired
        // Notify the user
        $userId = $license['user_id'];
        $user = $conn->query("SELECT * FROM users WHERE id = $userId")->fetch_assoc();
        $user_folder = $user['folder_path'];
        // Disable access: Change folder permissions
        if (file_exists($user_folder)) {
          $disable_file = exec("chmod -R 000 $user_folder");
          if ($disable_file) {
            send_telegram_notification("
          🚨 *License Expired Alert* 🚨
          
          📌 *User:* `{$user['username']}`  
          🔗 *Subdomain:* `{$user['subdomain']}`  
          🔑 *License Key:* `{$license['license_key']}`  
          📅 *Expiry Date:* `{$license['expiry_date']}`  
          📞 *Phone:* `{$user['phone']}`  
          📂 *Folder Path:* `{$user_folder}`  
          
          ⚠️ *The license has expired, and the file has been disabled!*
          ", $bot_token, $chat_id);
            //UPDATE STATUS
            $conn->query("UPDATE licenses SET status = 'expired' WHERE id = {$license['id']}");

            //return a json response
            echo json_encode(array("status" => "success", "message" => "License has expired and the file has been disabled!"));
          } else {
            send_telegram_notification("
          🚨 *License Expired Alert* 🚨
          
          📌 *User:* `{$user['username']}`  
          🔗 *Subdomain:* `{$user['subdomain']}`  
          🔑 *License Key:* `{$license['license_key']}`  
          📅 *Expiry Date:* `{$license['expiry_date']}`  
          📞 *Phone:* `{$user['phone']}`  
          📂 *Folder Path:* `{$user_folder}`  
          
          ⚠️ *The license has expired, but the file could not be disabled
          ", $bot_token, $chat_id);
          }

          //return a json response
          echo json_encode(array("status" => "error", "message" => "License has expired, but the file could not be disabled"));
        } else {
          send_telegram_notification("
          🚨 *License Expired Alert* 🚨
          
          📌 *User:* `{$user['username']}`  
          🔗 *Subdomain:* `{$user['subdomain']}`  
          🔑 *License Key:* `{$license['license_key']}`  
          📅 *Expiry Date:* `{$license['expiry_date']}`  
          📞 *Phone:* `{$user['phone']}`  
          📂 *Folder Path:* `{$user_folder}`  
          
          ⚠️ *The license has expired, but the file does not exist!*
          ", $bot_token, $chat_id);

          //return a json response
          echo json_encode(array("status" => "error", "message" => "License has expired, but the file does not exist"));
        }
      }
    }
  }

  $conn->close();
}



function activateLicense($licenseKey, $servername, $dbusername, $dbpassword, $dbname, $bot_token, $chat_id)
{
  // Establish database connection
  $conn = new mysqli($servername, $dbusername, $dbpassword, $dbname);
  if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
  }

  // Check if the license key exists
  $license = $conn->query("SELECT * FROM licenses WHERE license_key = '$licenseKey'")->fetch_assoc();
  if ($license) {
    $expiryDate = strtotime($license['expiry_date']);
    $today = strtotime(date('Y-m-d'));
    // License is active
    // Notify the user
    $userId = $license['user_id'];
    $user = $conn->query("SELECT * FROM users WHERE id = $userId")->fetch_assoc();
    $user_folder = $user['folder_path'];
    // Enable access: Change folder permissions
    if (file_exists($user_folder)) {
      $enable_file = exec("chmod -R 755 $user_folder");
      if ($enable_file) {
        send_telegram_notification("
          ✅ *License Activated* ✅
          
          📌 *User:* `{$user['username']}`  
          🔗 *Subdomain:* `{$user['subdomain']}`  
          🔑 *License Key:* `{$license['license_key']}`  
          📅 *Expiry Date:* `{$license['expiry_date']}`  
          📞 *Phone:* `{$user['phone']}`  
          📂 *Folder Path:* `{$user_folder}`  
          
          ✅ *The license has been activated successfully!*
          ", $bot_token, $chat_id);
        //UPDATE STATUS
        $conn->query("UPDATE licenses SET status = 'active' WHERE id = {$license['id']}");

        //return a json response
        echo json_encode(array("status" => "success", "message" => "The license has been activated successfully!"));
      } else {
        send_telegram_notification("
          ❌ *License Activation Failed* ❌

          📌 *User:* `{$user['username']}
          ` 🔗 *Subdomain:* `{$user['subdomain']}
          ` 🔑 *License Key:* `{$license['license_key']}
          ` 📅 *Expiry Date:* `{$license['expiry_date']}
          ` 📞 *Phone:* `{$user['phone']}
          ` 📂 *Folder Path:* `{$user_folder}
          ` ❌ *The license has expired, but the file could not be enabled
          ", $bot_token, $chat_id);

        //return a json response
        echo json_encode(array("status" => "error", "message" => "The license has expired, but the file could not be enabled"));
      }
    } else {
      send_telegram_notification("
          ❌ *License Activation Failed* ❌

          📌 *User:* `{$user['username']}
          ` 🔗 *Subdomain:* `{$user['subdomain']}
          ` 🔑 *License Key:* `{$license['license_key']}
          ` 📅 *Expiry Date:* `{$license['expiry_date']}
          ` 📞 *Phone:* `{$user['phone']}
          ` 📂 *Folder Path:* `{$user_folder}
          ` ❌ *The license has expired, but the file does not exist!
          ", $bot_token, $chat_id);

      //return a json response
      echo json_encode(array("status" => "error", "message" => "The license has expired, but the file does not exist"));
    }
  } else {
    send_telegram_notification("
          ❌ *License Activation Failed* ❌
          
          🔑 *License Key:* `$licenseKey`  
          
          ❌ *The license key does not exist!*
          ", $bot_token, $chat_id);

    //return a json response
    echo json_encode(array("status" => "error", "message" => "The license key does not exist"));
  }

  $conn->close();
}


function getCloudflareARecordId($cloudflare_zone_id, $cloudflare_token, $subdomain, $main_domain)
{
  $cloudflare_url = "https://api.cloudflare.com/client/v4/zones/$cloudflare_zone_id/dns_records?type=A&name=$subdomain.$main_domain";

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $cloudflare_url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer $cloudflare_token"
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  $data = json_decode($response, true);

  if ($data["success"] && count($data["result"]) > 0) {
    return $data["result"][0]["id"]; // Return the first A record ID
  } else {
    return false; // No record found
  }
}

function deleteCloudflareARecord($cloudflare_zone_id, $cloudflare_token, $dns_record_id)
{
  if (!$dns_record_id) {
    return "A record not found.";
  }

  $cloudflare_url = "https://api.cloudflare.com/client/v4/zones/$cloudflare_zone_id/dns_records/$dns_record_id";

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $cloudflare_url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
  curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer $cloudflare_token"
  ]);

  $response = curl_exec($ch);
  curl_close($ch);

  return $response;
}


function sendSMS($api_url, $number, $message)
{
  // Replace placeholders with actual values
  $api_url = str_replace(
    ['[text]', '[number]'],
    [urlencode($message), urlencode($number)],
    $api_url
  );
  $api_url = html_entity_decode($api_url);
  // Initialize cURL session
  $ch = curl_init($api_url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  $response = curl_exec($ch);
  curl_close($ch);
  return $response;
}

function sendEmail($mysqli, $email, $subject, $message)
{

  // Get settings from database
  $stmt = $mysqli->prepare("SELECT setting_name, setting_value FROM settings WHERE setting_name IN ('smtp_host', 'smtp_port', 'smtp_user', 'smtp_pass')");
  $stmt->execute();
  $result = $stmt->get_result();
  $settings = [];
  while ($row = $result->fetch_assoc()) {
    $settings[$row['setting_name']] = $row['setting_value'];
  }
  $stmt->close();
  $host = $settings['smtp_host'] ?? '';
  $port = $settings['smtp_port'] ?? '';
  $user = $settings['smtp_user'] ?? '';
  $pass = $settings['smtp_pass'] ?? '';
  $res = test_smtp_settings($host, $port, $user, $pass, $email, $subject, $message);
  if ($res === true) {
    return "Test email sent successfully to $email.";
  } else {
    return "Failed to send test email: $res";
  }
}


function test_smtp_settings($host, $port, $user, $pass, $email, $subject, $message)
{
  $mail = new PHPMailer(true); // Enable exceptions
  try {
    $mail->isSMTP();
    $mail->SMTPAuth = true;
    $mail->SMTPSecure = ($port == 465) ? 'ssl' : 'tls';  // Auto-detect security type
    $mail->Host = $host;
    $mail->Port = $port;
    $mail->CharSet = 'UTF-8';
    // SMTP credentials
    $mail->Username = $user;
    $mail->Password = $pass;
    // Set sender and recipient
    $mail->setFrom($user);
    $mail->addAddress($email);
    // Email content
    $mail->isHTML(true);
    $mail->Subject = $subject;
    $mail->Body = $message;
    // Ignore SSL verification issues (not recommended for production)
    $mail->SMTPOptions = array('ssl' => array(
      'verify_peer' => false,
      'verify_peer_name' => false,
      'allow_self_signed' => true
    ));
    // Send the email
    if ($mail->send()) {
      return true; // Email sent successfully
    } else {
      return  $mail->ErrorInfo; // Error message
    }
  } catch (Exception $e) {
    return "Mailer Error: " . $mail->ErrorInfo;
  }
}

/**
 * Check if the system is fully installed
 * @return bool True if system is installed, false otherwise
 */
function isSystemInstalled() {
    $config_file = '';
    if (file_exists('config.php')) {
        $config_file = 'config.php';
    }
    
    if (!$config_file) {
        return false;
    }
    
    try {
        include $config_file;
        
        $host = defined('DB_HOST') ? constant('DB_HOST') : (defined('MYSQL_HOST') ? constant('MYSQL_HOST') : null);
        $database = defined('DB_NAME') ? constant('DB_NAME') : (defined('MYSQL_DATABASE') ? constant('MYSQL_DATABASE') : null);
        $user = defined('DB_USER') ? constant('DB_USER') : (defined('MYSQL_USER') ? constant('MYSQL_USER') : null);
        $password = defined('DB_PASS') ? constant('DB_PASS') : (defined('MYSQL_PASSWORD') ? constant('MYSQL_PASSWORD') : null);
        
        if (!$host || !$database || $user === null) {
            return false;
        }
        
        $conn = new PDO(
            "mysql:host=" . $host . ";dbname=" . $database,
            $user,
            $password
        );
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        // Check if core tables exist
        $stmt = $conn->prepare("SHOW TABLES LIKE 'system_user'");
        $stmt->execute();
        $system_user_exists = ($stmt->rowCount() > 0);
        
        $stmt = $conn->prepare("SHOW TABLES LIKE 'subscription_plans'");
        $stmt->execute();
        $subscription_plans_exists = ($stmt->rowCount() > 0);
        
        $stmt = $conn->prepare("SHOW TABLES LIKE 'settings'");
        $stmt->execute();
        $settings_exists = ($stmt->rowCount() > 0);
        
        return ($system_user_exists && $subscription_plans_exists && $settings_exists);
        
    } catch (Exception $e) {
        return false;
    }
}
