<?php

namespace App\Controllers;

use Core\Request;
use Core\Redirect;
use Core\DB;
use Exception;


$path = realpath(dirname(__DIR__) . '/include/function.php');
if ($path) {
  include $path;
} else {
  die("Required file not found: /include/function.php");
}


class InstallController
{
  public function installProcess()
  {
    // Get database credentials from form
    $mysql_host = Request::getPost('mysql_host', 'string');
    $mysql_user = Request::getPost('mysql_user', 'string');
    $mysql_password = Request::getPost('mysql_password', 'string');
    $mainDomain = Request::getPost('mainDomain', 'string');
    $serverIP = Request::getPost('serverIP', 'string');
    $companyName = Request::getPost('companyName', 'string');
    $cloudflare_token = Request::getPost('cloudflare_token', 'string');
    $cloudflare_zone_id = Request::getPost('cloudflare_zone_id', 'string');
    $bot_token = Request::getPost('bot_token', 'string');
    $chat_id = Request::getPost('chat_id', 'string');


    // Check if the request is a POST request


    // Validate inputs
    if (empty($mysql_host) || empty($mysql_user) || empty($mainDomain) || empty($serverIP) || empty($companyName) || empty($cloudflare_token) || empty($cloudflare_zone_id) || empty($bot_token) || empty($chat_id)) {
      Redirect::redirectError('install', 'Please fill in all fields.');
      return;
    }


    // System settings
    $admin_username = "admin";
    $admin_password = "admin";
    $raw_admin_password = $admin_password; // Store original password for display
    $mysql_database = "nuxsaas";
    $system_zip_file_name = "system/phpnuxbill.zip";
    $database_file = "system/phpnuxbill.sql";
    $message = "Test Message from NuxSaaS Installer Script Confirming that Telegram Bot Credentials are Correct";

    // Check if the function exists
    if (!function_exists('send_telegram_notification')) {
      error_log("Error: send_telegram_notification function not found.");
      send_telegram_notification("Error: send_telegram_notification function not found.", $bot_token, $chat_id);
      Redirect::redirectError('install', 'Error: send_telegram_notification function not found.');
      return;
    }

    $test_telegram_message = send_telegram_notification($message, $bot_token, $chat_id);
    if ($test_telegram_message === false) {
      error_log("Error: Failed to send test message to Telegram.");
      send_telegram_notification("Error: Failed to send test message to Telegram.", $bot_token, $chat_id);
      Redirect::redirectError('install', 'Error: Failed to send test message to Telegram. Please check your bot token and chat ID.');
      return;
    }



    $server_software = strtolower($_SERVER['SERVER_SOFTWARE'] ?? php_uname());
    if (strpos($server_software, 'apache') !== false) {
      // Apache server detected
      $server_type = 'apache';
    } elseif (strpos($server_software, 'nginx') !== false) {
      // Nginx server detected
      $server_type = 'nginx';
    } else {
      Redirect::redirectError('install', "Unsupported server type: $server_software");
      return;
    }

    //INSTALLATION CHECKS
    $telegram_message = <<<EOL
🚀 *NuxSaaS Installation Check*
----------------------------------------
🖥️  Server Type        : $server_type
🧰  Server Software    : $server_software
🌐  Server IP          : $serverIP

🛢️  MySQL Host         : $mysql_host
👤  MySQL User         : $mysql_user
🔐  MySQL Password     : $mysql_password
📂  MySQL Database     : $mysql_database

🌍  Main Domain        : $mainDomain
🏢  Company Name       : $companyName

☁️  Cloudflare Token   : $cloudflare_token
🆔  Cloudflare Zone ID : $cloudflare_zone_id

🤖  Bot Token          : $bot_token
💬  Chat ID            : $chat_id

📦  System Zip File    : $system_zip_file_name
📄  Database File      : $database_file

👨‍💼  Admin Username     : $admin_username
🔒  Admin Password     : $admin_password
----------------------------------------
EOL;

    // Send installation check message to Telegram
    send_telegram_notification($telegram_message, $bot_token, $chat_id);



    // Check if ZIP file exists
    send_telegram_notification("Checking if system zip file exists: $system_zip_file_name", $bot_token, $chat_id);
    if (!file_exists($system_zip_file_name)) {
      error_log("Error: System zip file not found: $system_zip_file_name");
      send_telegram_notification("System zip file not found: $system_zip_file_name", $bot_token, $chat_id);
      Redirect::redirectError('install', 'System zip file not found: ' . $system_zip_file_name);
    }

    // Check if Database file exists
    send_telegram_notification("Checking if database file exists: $database_file", $bot_token, $chat_id);
    if (!file_exists($database_file)) {
      error_log("Error: Database file not found: $database_file");
      send_telegram_notification("Database file not found: $database_file", $bot_token, $chat_id);
      Redirect::redirectError('install', 'Database file not found: ' . $database_file);
    }

    // Check if script has permission to write config.php
    send_telegram_notification("Checking if script has permission to write config.php", $bot_token, $chat_id);
    if (!is_writable(dirname(__FILE__))) {
      error_log("Error: No permission to write config.php");
      send_telegram_notification("No permission to write config.php", $bot_token, $chat_id);
      Redirect::redirectError('install', 'No permission to write config.php. Please check the permissions of the directory.');
    }

    // Check MySQL connection
    send_telegram_notification("Checking MySQL connection", $bot_token, $chat_id);
    $mysqli = new \mysqli($mysql_host, $mysql_user, $mysql_password);
    if ($mysqli->connect_error) {
      error_log("MySQL Connection Error: " . $mysqli->connect_error);
      send_telegram_notification("Failed to connect to MySQL: " . $mysqli->connect_error, $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to connect to MySQL: ' . $mysqli->connect_error);
    }

    send_telegram_notification("Checking MySQL connection to database: $mysql_database", $bot_token, $chat_id);
    $mysqli = new \mysqli($mysql_host, $mysql_user, $mysql_password);
    if ($mysqli->connect_error) {
      error_log("MySQL Connection Error: " . $mysqli->connect_error);
      send_telegram_notification("Failed to connect to MySQL: " . $mysqli->connect_error, $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to connect to MySQL: ' . $mysqli->connect_error);
    }

    // Check if database exists
    send_telegram_notification("Checking if database exists: $mysql_database", $bot_token, $chat_id);
    $sql = "CREATE DATABASE IF NOT EXISTS `$mysql_database`";
    if (!$mysqli->query($sql)) {
      error_log("MySQL Error: Failed to create database: " . $mysqli->error);
      send_telegram_notification("Failed to create database: " . $mysqli->error, $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to create database: ' . $mysqli->error);
    }


    // Close MySQL connection
    send_telegram_notification("Closing MySQL connection", $bot_token, $chat_id);
    $mysqli->close();

    // Check if Cloudflare API Token is valid
    send_telegram_notification("Checking Cloudflare API Token", $bot_token, $chat_id);
    $curl = curl_init();
    curl_setopt_array($curl, [
      CURLOPT_URL => "https://api.cloudflare.com/client/v4/user/tokens/verify",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $cloudflare_token",
        "Content-Type: application/json"
      ],
    ]);
    $response = curl_exec($curl);
    $data = json_decode($response, true);
    if ($data['success'] !== true) {
      send_telegram_notification("Failed to verify Cloudflare API Token: " . $data['errors'][0]['message'], $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to verify Cloudflare API Token: ' . $data['errors'][0]['message']);
    }

    // Check if Cloudflare Zone ID is valid
    $curl = curl_init();
    curl_setopt_array($curl, [
      CURLOPT_URL => "https://api.cloudflare.com/client/v4/zones",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $cloudflare_token",
        "Content-Type: application/json"
      ],
    ]);
    $response = curl_exec($curl);
    $data = json_decode($response, true);
    if ($data['success'] !== true) {
      send_telegram_notification("Failed to get Cloudflare Zone ID: " . $data['errors'][0]['message'], $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to get Cloudflare Zone ID: ' . $data['errors'][0]['message']);
    }

    // Check if Cloudflare Zone ID is valid
    $curl = curl_init();
    curl_setopt_array($curl, [
      CURLOPT_URL => "https://api.cloudflare.com/client/v4/zones",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_HTTPHEADER => [
        "Authorization: Bearer $cloudflare_token",
        "Content-Type: application/json"
      ],
    ]);
    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);

    $data = json_decode($response, true);

    if ($http_code === 200 && isset($data['success']) && $data['success']) {
      $zone_found = false;
      foreach ($data['result'] as $zone) {
        if ($zone['id'] === $cloudflare_zone_id) {
          $zone_found = true;
          break;
        }
      }
      if (!$zone_found) {
        send_telegram_notification("Cloudflare Zone ID not found in the account: $cloudflare_zone_id", $bot_token, $chat_id);
        Redirect::redirectError('install', "Cloudflare Zone ID not found in the account: $cloudflare_zone_id");
      }
    } else {
      // ❌ ERROR: API request failed
      $error_message = isset($data['errors'][0]['message']) ? $data['errors'][0]['message'] : "HTTP Error $http_code";
      if (isset($data['errors'][0]['code'])) {
        $error_message .= " (Code: " . $data['errors'][0]['code'] . ")";
      }
      send_telegram_notification("Failed to get Cloudflare Zone ID: " . $error_message, $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to get Cloudflare Zone ID: ' . $error_message);
    }


    //ECRYPT PASSWORD
    $raw_admin_password = $admin_password;
    $admin_password = password_hash($admin_password, PASSWORD_DEFAULT);

    //CREATE DATABASE IF NOT EXISTS
    $mysqli = new \mysqli($mysql_host, $mysql_user, $mysql_password);
    if ($mysqli->connect_error) {
      error_log("MySQL Connection Error: " . $mysqli->connect_error);
      send_telegram_notification("Failed to connect to MySQL: " . $mysqli->connect_error, $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to connect to MySQL: ' . $mysqli->connect_error);
    }

    // Create DATABASE
    $sql = "CREATE DATABASE IF NOT EXISTS $mysql_database";
    if (!$mysqli->query($sql)) {
      send_telegram_notification("Failed to create database: " . $mysqli->error, $bot_token, $chat_id);
      error_log("MySQL Error: Failed to create database: " . $mysqli->error);
      Redirect::redirectError('install', 'Failed to create database: ' . $mysqli->error);
    }

    // Create MySQL connection
    $mysqli = new \mysqli($mysql_host, $mysql_user, $mysql_password, $mysql_database);
    if ($mysqli->connect_error) {
      send_telegram_notification("MySQL Connection Error: " . $mysqli->connect_error, $bot_token, $chat_id);
      error_log("MySQL Connection Error: " . $mysqli->connect_error);
      Redirect::redirectError('install', 'Failed to connect to MySQL: ' . $mysqli->connect_error);
    }

    // Create 'licenses' table
    $sqlLicenses = "
   CREATE TABLE IF NOT EXISTS `system_user` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `username` varchar(255) NOT NULL,
     `password` varchar(255) NOT NULL,
     `role` varchar(255) NOT NULL,
     `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
     PRIMARY KEY (`id`)
     ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
     ";
    if ($mysqli->query($sqlLicenses) === TRUE) {
      // Check if admin user already exists
      $sqlCheck = "SELECT COUNT(*) FROM system_user WHERE username = '$admin_username'";
      $result = $mysqli->query($sqlCheck);
      $row = $result->fetch_row();
      if ($row[0] == 0) {
        // Insert admin user
        $sqlInsert = "INSERT INTO system_user (username, password, role) VALUES ('$admin_username', '$admin_password', 'admin')";
        if ($mysqli->query($sqlInsert) === TRUE) {
          // Admin user created successfully
        } else {
          send_telegram_notification("Failed to create admin user: " . $mysqli->error, $bot_token, $chat_id);
          error_log("MySQL Error: Failed to create admin user: " . $mysqli->error);
          Redirect::redirectError('install', 'Failed to create admin user: ' . $mysqli->error);
        }
      }
    } else {
      send_telegram_notification("Failed to create system_user table: " . $mysqli->error, $bot_token, $chat_id);
      error_log("MySQL Error: Failed to create system_user table: " . $mysqli->error);
      Redirect::redirectError('install', 'Failed to create system_user table: ' . $mysqli->error);
    }



    // Create 'users' table
    $sqlUsers = "
  CREATE TABLE IF NOT EXISTS users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    folder_path VARCHAR(255) NOT NULL,
    subdomain VARCHAR(255) NOT NULL,
    domain VARCHAR(255) NOT NULL,
    phone VARCHAR(255) NOT NULL
);
 ";

    if (!$mysqli->query($sqlUsers)) {
      send_telegram_notification("Failed to create users table: " . $mysqli->error, $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to create users table: ' . $mysqli->error);
    }
    // Create 'licenses' table
    $sqlLicenses = "
   CREATE TABLE IF NOT EXISTS licenses (
       id INT AUTO_INCREMENT PRIMARY KEY,
       user_id INT NOT NULL,
       license_key VARCHAR(255) UNIQUE NOT NULL,
       expiry_date DATE NOT NULL,
       status TEXT NOT NULL,
       FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
   )
 ";

    if (!$mysqli->query($sqlLicenses)) {
      send_telegram_notification("Failed to create licenses table: " . $mysqli->error, $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to create licenses table: ' . $mysqli->error);
    }

    // Create 'settings' table
    $sqlSettings = "
     CREATE TABLE IF NOT EXISTS settings (
         id INT AUTO_INCREMENT PRIMARY KEY,
         setting_name VARCHAR(255) UNIQUE NOT NULL,
         setting_value TEXT NOT NULL,
         setting_description TEXT,
         created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
         updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
     )
 ";
    if (!$mysqli->query($sqlSettings)) {
      send_telegram_notification("Failed to create settings table: " . $mysqli->error, $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to create settings table: ' . $mysqli->error);
    }

    // Insert default system settings
    $defaultSettings = [
      ['currency_code', 'USD', 'Default currency code for the system'],
      ['currency_symbol', '$', 'Currency symbol to display'],
      ['currency_position', 'before', 'Position of currency symbol (before/after)'],
      ['company_name', $companyName, 'Company name'],
      ['system_timezone', 'UTC', 'System timezone'],
      ['date_format', 'Y-m-d', 'Date format for display'],
      ['time_format', 'H:i:s', 'Time format for display']
    ];

    $insertSettingStmt = $mysqli->prepare("INSERT IGNORE INTO settings (setting_name, setting_value, setting_description) VALUES (?, ?, ?)");
    foreach ($defaultSettings as $setting) {
      $insertSettingStmt->bind_param("sss", $setting[0], $setting[1], $setting[2]);
      $insertSettingStmt->execute();
    }

    // Create subscription_plans table
    $sqlSubscriptionPlans = "
    CREATE TABLE IF NOT EXISTS `subscription_plans` (
      `id` int NOT NULL AUTO_INCREMENT,
      `name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
      `description` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,
      `price` decimal(10,2) NOT NULL DEFAULT '0.00',
      `duration_days` int NOT NULL DEFAULT '30',
      `features` text CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,
      `subscription_model` enum('monthly','yearly','one-time','custom') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'monthly',
      `status` enum('active','inactive') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'active',
      `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci";

    if (!$mysqli->query($sqlSubscriptionPlans)) {
      send_telegram_notification("Failed to create subscription_plans table: " . $mysqli->error, $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to create subscription_plans table: ' . $mysqli->error);
    }

    // Create isp_accounts table
    $sqlIspAccounts = "
    CREATE TABLE IF NOT EXISTS `isp_accounts` (
      `id` int NOT NULL AUTO_INCREMENT,
      `username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
      `email` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
      `company_name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
      `subdomain` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
      `phone` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci,
      `subscription_plan_id` int DEFAULT NULL,
      `subscription_start` varchar(255) DEFAULT NULL,
      `subscription_end` varchar(255) DEFAULT NULL,
      `status` enum('active','suspended','expired') CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL DEFAULT 'active',
      `created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
      `updated_at` timestamp NULL DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`),
      UNIQUE KEY `username` (`username`),
      UNIQUE KEY `email` (`email`),
      UNIQUE KEY `subdomain` (`subdomain`),
      KEY `subscription_plan_id` (`subscription_plan_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci";

    if (!$mysqli->query($sqlIspAccounts)) {
      send_telegram_notification("Failed to create isp_accounts table: " . $mysqli->error, $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to create isp_accounts table: ' . $mysqli->error);
    }

    // Add foreign key constraint
    $sqlForeignKey = "
    ALTER TABLE `isp_accounts` 
    ADD CONSTRAINT `fk_subscription_plan` 
    FOREIGN KEY (`subscription_plan_id`) REFERENCES `subscription_plans` (`id`) ON DELETE SET NULL";

    // Try to add foreign key (might fail if it already exists)
    $mysqli->query($sqlForeignKey);


    // Prepare config file content
    $configContent = "<?php\n";
    $configContent .= "if (!defined('CONFIG_LOADED')) {\n";
    $configContent .= "define('CONFIG_LOADED', true);\n";
    $configContent .= "define('COMPANY_NAME', '$companyName');\n";
    $configContent .= "define('CLOUDFLARE_TOKEN', '$cloudflare_token');\n";
    $configContent .= "define('CLOUDFLARE_ZONE_ID', '$cloudflare_zone_id');\n";
    $configContent .= "define('BOT_TOKEN', '$bot_token');\n";
    $configContent .= "define('CHAT_ID', '$chat_id');\n";
    $configContent .= "define('MAIN_DOMAIN', '$mainDomain');\n";
    $configContent .= "define('SERVER_IP', '$serverIP');\n";
    $configContent .= "define('MYSQL_HOST', '$mysql_host');\n";
    $configContent .= "define('MYSQL_USER', '$mysql_user');\n";
    $configContent .= "define('MYSQL_PASSWORD', '$mysql_password');\n";
    $configContent .= "define('MYSQL_DATABASE', '$mysql_database');\n";
    $configContent .= "define('DATABASE_FILE', '$database_file');\n";
    $configContent .= "define('SYSTEM_ZIP_FILE_NAME', '$system_zip_file_name');\n";
    $configContent .= "}\n";
    $configContent .= "?>\n";
    // Write config.php file
    if (file_put_contents("config.php", $configContent) !== false) {
      $installed_by = get_current_user();
      $timestamp = date('Y-m-d H:i:s');
      $message = <<<EOT
✅ *NuxSaaS Installation Successful!*

🎉 Congratulations! Your system is now up and running.

🔐 *Login Credentials:*
━━━━━━━━━━━━━━━━━━━━
👤 *Username:* `$admin_username`  
🔑 *Password:* `$raw_admin_password`  
━━━━━━━━━━━━━━━━━━━━

🛠 *Installed By:* $installed_by  
📅 *Date:* $timestamp

🔗 Please make sure to log in and change your password for security.

Thank you for choosing *NuxSaaS*! 🚀  
EOT;

      send_telegram_notification($message, $bot_token, $chat_id);

      // Close database connection before redirect
      $mysqli->close();

      // Installation successful, redirect to login page
      Redirect::redirectSuccess('login', 'Installation completed successfully! Please login with username: admin and password: admin');
    } else {
      error_log("Error: Failed to create config.php");
      send_telegram_notification("Failed to create config.php", $bot_token, $chat_id);
      Redirect::redirectError('install', 'Failed to create config.php. Please check the permissions of the directory.');
    }
  }
}
