<?php

namespace App\Controllers;

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

include realpath(dirname(__DIR__) . '/include/function.php');
include_once realpath(dirname(__DIR__) . '/../config.php');

class AccountAction
{
  public function suspend()
  {
    $user_id = intval($_GET['user_id']);
    // Get database connection
    $db = new DB();
    $conn = $db->getConnection();
    // Fetch user details
    $stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    // Ensure user exists
    if (!$user) {
      Redirect::redirectError('accounts', 'User not found');
    }
    $folder_path = $user['folder_path'];
    $username = $user['username'];
    $subdomain = $user['subdomain'];
    // Get licenses from database
    $stmt = $conn->prepare("SELECT * FROM licenses WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $license = $result->fetch_assoc();
    $stmt->close();
    // Ensure license exists
    if (!$license) {
      Redirect::redirectError('accounts', 'License not found for this user');
    }
    $license_key = $license['license_key'];
    $license_status = $license['status'];
    $license_expiry = $license['expiry_date'];
    // Path for the suspension page
    $suspend_path = $folder_path . '/index.html';
    // Check if file exists and delete it
    if (file_exists($suspend_path)) {
      unlink($suspend_path);
    }
    // Load suspension template
    $template_path =  realpath(dirname(__DIR__) . '/include/suspend.html');
    if (!file_exists($template_path)) {
      Redirect::redirectError('accounts', 'Template file not found');
    }
    $suspend_content = file_get_contents($template_path);
    // Replace placeholders with actual values
    $suspend_content = str_replace("{username}", htmlspecialchars($username), $suspend_content);
    $suspend_content = str_replace("{license_key}", htmlspecialchars($license_key), $suspend_content);
    $suspend_content = str_replace("{license_status}", htmlspecialchars($license_status), $suspend_content);
    $suspend_content = str_replace("{license_expiry}", htmlspecialchars($license_expiry), $suspend_content);
    // Write the suspension page
    if (file_put_contents($suspend_path, $suspend_content) === false) {
      Redirect::redirectError('accounts', 'Failed to create suspension page');
    }
    // Store license in a file inside the user's folder
    $license_file_path = $folder_path . '/license.txt';
    $license_content = "License Key: " . htmlspecialchars($license_key) . "\n" .
      "Expiry Date: " . htmlspecialchars($license_expiry) . "\n";
    if (file_put_contents($license_file_path, $license_content) === false) {
      Redirect::redirectError('accounts', 'Failed to create license file');
    }
    // Update user status in the database
    $stmt = $conn->prepare("UPDATE licenses SET status = 'inactive' WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->close();
    $conn->close();
    Redirect::redirectSuccess('accounts', 'User suspended successfully');
  }

  public function renew()
  {
    $user_id = intval($_GET['user_id']);
    $db = new DB();
    $conn = $db->getConnection();
    // Fetch user details
    $stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    // Ensure user exists
    if (!$user) {
      Redirect::redirectError('accounts', 'User not found');
    }
    $folder_path = $user['folder_path'];
    $username = $user['username'];
    $subdomain = $user['subdomain'];
    // Path for the suspension page
    $suspend_path = $folder_path . '/index.html';
    //CHECK IF FILE EXISTS
    if (file_exists($suspend_path)) {
      // If the file exists, delete it
      unlink($suspend_path);
    }
    //RENEW LICENSE
    $stmt = $conn->prepare("SELECT * FROM licenses WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $license = $result->fetch_assoc();
    $stmt->close();
    // Ensure license exists
    if (!$license) {
      Redirect::redirectError('accounts', 'License not found for this user');
    }
    $license_key = $license['license_key'];
    $license_status = $license['status'];
    $license_expiry = $license['expiry_date'];
    // update license expiry date with 30 days
    $new_expiry_date = date('Y-m-d', strtotime('+30 days')); // Extend by 30 days
    $stmt = $conn->prepare("UPDATE licenses SET expiry_date = ? WHERE user_id = ?");
    $stmt->bind_param("si", $new_expiry_date, $user_id);
    $stmt->execute();
    $stmt->close();
    // Create new license file
    $license_file_path = $folder_path . '/license.txt';
    $license_content = "License Key: " . htmlspecialchars($license_key) . "\n" .
      "Expiry Date: " . htmlspecialchars($new_expiry_date) . "\n";
    if (file_put_contents($license_file_path, $license_content) === false) {
      Redirect::redirectError('accounts', 'Failed to create license file');
    }
    // Update user status in the database
    $stmt = $conn->prepare("UPDATE licenses SET status = 'active' WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $stmt->close();
    $conn->close();
    Redirect::redirectSuccess('accounts', 'User renewed successfully');
  }

  public function delete()
  {
    $user_id = intval($_GET['user_id']);
    $db = new DB();
    $conn = $db->getConnection();
    // Fetch user details
    $stmt = $conn->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $user = $result->fetch_assoc();
    $stmt->close();
    // Ensure user exists
    if (!$user) {
      Redirect::redirectError('accounts', 'User not found');
    }
    $folder_path = $user['folder_path'];
    $username = $user['username'];
    $subdomain = $user['subdomain'];

    $db_for_user = preg_replace('/[^a-zA-Z0-9_]/', '', $username); // Sanitize DB name

    $main_domain = MAIN_DOMAIN; // Ensure this is defined in your config.php
    $server_ip = SERVER_IP; // Ensure this is defined in your config.php
    $cloudflare_token = CLOUDFLARE_TOKEN; // Ensure this is defined in your config.php
    $cloudflare_zone_id = CLOUDFLARE_ZONE_ID; // Ensure this is defined in your config.php
    $bot_token = BOT_TOKEN; // Ensure this is defined in your config.php
    $chat_id = CHAT_ID; // Ensure this is defined in your config.php

    // DELETE FOLDER
    if (is_dir($folder_path)) {
      $command = "rm -rf " . escapeshellarg($folder_path);
      exec($command, $output, $return_var);
      if ($return_var !== 0) {
        send_telegram_notification("Error deleting folder: " . implode("\n", $output), $bot_token, $chat_id);
        Redirect::redirectError('accounts', 'Error deleting folder');
      }
    }

    // DELETE APACHE CONF FILE
    $server_software = strtolower($_SERVER['SERVER_SOFTWARE'] ?? php_uname());
    if (strpos($server_software, 'apache') !== false) {
      $apache_conf_file = "/etc/apache2/sites-available/$username.conf";
      if (file_exists($apache_conf_file)) {
        $command = "rm -f " . escapeshellarg($apache_conf_file);
        exec($command, $output, $return_var);
        if ($return_var !== 0) {
          send_telegram_notification("Error deleting Apache conf file: " . implode("\n", $output), $bot_token, $chat_id);
          Redirect::redirectError('accounts', 'Error deleting Apache conf file');
        }
      }
    }

    // DELETE MYSQL DATABASE
    $conn_con = new \mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD);
    if ($conn_con->connect_error) {
      send_telegram_notification("Error connecting to MySQL: " . $conn_con->connect_error, $bot_token, $chat_id);
      Redirect::redirectError('accounts', 'Error connecting to MySQL');
    }

    $drop_db_query = "DROP DATABASE IF EXISTS `$db_for_user`";
    if (!$conn_con->query($drop_db_query)) {
      send_telegram_notification("Error dropping database: " . $conn_con->error, $bot_token, $chat_id);
      Redirect::redirectError('accounts', 'Error dropping database');
    }
    $conn_con->close();

    // DELETE FROM CLOUDFLARE
    $dns_record_id = getCloudflareARecordId($cloudflare_zone_id, $cloudflare_token, $subdomain, $main_domain);
    if ($dns_record_id) {
      $delete_cloud_res = deleteCloudflareARecord($cloudflare_zone_id, $cloudflare_token, $dns_record_id);
      $delete_cloud_res_obj = json_decode($delete_cloud_res, true);

      if (!isset($delete_cloud_res_obj['success']) || !$delete_cloud_res_obj['success']) {
        send_telegram_notification("Failed to delete Cloudflare A record: " . json_encode($delete_cloud_res_obj), $bot_token, $chat_id);
        Redirect::redirectError('accounts', 'Failed to delete Cloudflare A record');
      }
    } else {
      send_telegram_notification("No DNS record found for $subdomain.$main_domain", $bot_token, $chat_id);
      Redirect::redirectError('accounts', 'No DNS record found for this user');
    }

    // DELETE USER FROM DATABASE
    $stmt = $conn->prepare("DELETE FROM users WHERE id = ?");
    $stmt->bind_param("i", $user_id);
    if (!$stmt->execute()) {
      send_telegram_notification("Error deleting user: " . $stmt->error, $bot_token, $chat_id);
      Redirect::redirectError('accounts', 'Error deleting user');
    }
    $stmt->close();


    // DELETE USER FROM DATABASE
    $stmt = $conn->prepare("DELETE FROM  isp_accounts WHERE username = ?");
    $stmt->bind_param("s", $username);
    if (!$stmt->execute()) {
      send_telegram_notification("Error deleting user: " . $stmt->error, $bot_token, $chat_id);
      Redirect::redirectError('accounts', 'Error deleting user');
    }
    $stmt->close();

    // DELETE LICENSE FROM DATABASE
    $stmt = $conn->prepare("DELETE FROM licenses WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    if (!$stmt->execute()) {
      send_telegram_notification("Error deleting license: " . $stmt->error, $bot_token, $chat_id);
      Redirect::redirectError('accounts', 'Error deleting license');
    }
    $stmt->close();

    $conn->close();


    // Cron jobs to remove
    $cronToRemove = [
      "*/5 * * * * cd /var/www/html/$username/system/ && /usr/bin/php cron.php",
      "0 * * * * cd /var/www/html/$username/system/ && /usr/bin/php cron.php",
      "0 7 * * * cd /var/www/html/$username/system/ && /usr/bin/php cron_reminder.php"
    ];

    function getCurrentCrontab(): array
    {
      exec('crontab -l 2>/dev/null', $output, $exitCode);
      return $exitCode === 0 ? $output : [];
    }

    function saveCrontab(array $lines): void
    {
      $tempFile = tempnam(sys_get_temp_dir(), 'cron_');
      file_put_contents($tempFile, implode(PHP_EOL, $lines) . PHP_EOL);
      exec("crontab $tempFile");
      unlink($tempFile);
    }

    // Get existing cron jobs
    $currentCrons = getCurrentCrontab();

    // Filter out unwanted jobs
    $updatedCrons = array_filter($currentCrons, function ($cron) use ($cronToRemove) {
      return !in_array(trim($cron), $cronToRemove);
    });

    // Determine what changed
    $removedJobs = array_diff($currentCrons, $updatedCrons);

    // Save new crontab if changes occurred
    if (count($removedJobs) > 0) {
      saveCrontab($updatedCrons);
      $statusMsg = "🗑️ Removed cron jobs:<br><code>" . implode("<br>", $removedJobs) . "</code>";
    } else {
      $statusMsg = "❌ No matching cron jobs found to remove.";
    }

    // Send Telegram notification
    send_telegram_notification("Cron job Res : " . $statusMsg, $bot_token, $chat_id);




    send_telegram_notification("User $username deleted successfully", $bot_token, $chat_id);
    Redirect::redirectSuccess('accounts', 'User deleted successfully');
  }
}
