<?php
if(!defined('BASEPATH')) {
   die('Direct access to the script is not allowed');
}
if( $panel["panel_status"] == "suspended" ): include 'app/views/frozen.twig';exit(); endif;
if( $panel["panel_status"] == "frozen" ): include 'app/views/frozen.twig';exit(); endif;
$title .= $languageArray["account.title"];

if( $_SESSION["msmbilisim_userlogin"] != 1  || $user["client_type"] == 1  ){
  header("Location:".site_url('logout'));
}
if(route(1) == "change_currency"){
  
$rate_key = $_POST["rate_key"];
$rate_sym = $_POST["sym"];

$currencies = $conn->prepare("SELECT * FROM currencies WHERE is_enable=1");
$currencies->execute();
$currencies = $currencies->fetchAll(PDO::FETCH_ASSOC);
$currencies = array_group_by($currencies,"currency_code");

if(array_key_exists($rate_key,$currencies) && $settings["site_currency_converter"] == "1"){
 $update = $conn->prepare("UPDATE clients SET currency_type=:currency_type WHERE client_id=:id ");
 $update = $update->execute(array("id"=>$user["client_id"],"currency_type"=>$rate_key));

$resp = array(
"success" => true,
"message" => "Success"
);

setcookie("currency_hash",get_currency_hash_by_code($rate_key),strtotime('+28 days'),'/',null,null,true);
}
else {
header("Location:".site_url(''));
}
 } elseif( route(1) == "newapikey" ){
    $conn->beginTransaction();
    $insert= $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date ");
    $insert= $insert->execute(array("c_id"=>$user["client_id"],"action"=>"API Key changed","ip"=>GetIP(),"date"=>date("Y-m-d H:i:s") ));
    $apikey = CreateApiKey(["email"=>$user["email"],"username"=>$user["username"]]);
    $update = $conn->prepare("UPDATE clients SET apikey=:key WHERE client_id=:id ");
    $update = $update->execute(array("id"=>$user["client_id"],"key"=>$apikey ));
    if( $update ):
if( $settings["alert_apimail"]  == "2" ){
// api key change mail 
 $site_name = $settings["site_name"];
$htmlContent = "<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>API Key Update Notification</title>
  <style>
    /* Basic email styling */
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f4f4f4;
      color: #333;
      text-align: center;
    }
    .email-container {
      width: 100%;
      max-width: 600px;
      margin: 20px auto;
      background-color: #ffffff;
      padding: 30px;
      box-sizing: border-box;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
      border-radius: 8px;
    }
    
    /* Full-width header */
    .header-container {
      background-color: #d9534f;
      padding: 20px;
      margin: -30px -30px 20px -30px; /* Extends full width */
      text-align: center;
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
    }
    .header {
      color: white;
      font-size: 22px;
      font-weight: bold;
    }
    
    p {
      font-size: 16px;
      line-height: 1.6;
      padding: 5px 10px;
      text-align: center;
    }
    a {
      color: #007bff;
      text-decoration: none;
    }
    a:hover {
      text-decoration: underline;
    }

    /* Important red warning box */
    .warning {
      background-color: #f8d7da;
      border: 2px solid #f5c6cb;
      color: #721c24;
      padding: 20px;
      margin-top: 20px;
      border-radius: 8px;
      font-size: 18px;
      font-weight: bold;
      text-align: center;
    }

    /* Button */
    .button {
      background-color: #007bff;
      color: white;
      text-decoration: none;
      padding: 12px 25px;
      border-radius: 5px;
      display: inline-block;
      font-size: 16px;
      text-align: center;
      margin-top: 20px;
    }
    .button:hover {
      background-color: #0056b3;
    }

    /* Mobile responsiveness */
    @media only screen and (max-width: 600px) {
      .email-container {
        padding: 20px;
      }
      .header-container {
        padding: 15px;
      }
      .header {
        font-size: 20px;
      }
      .warning {
        font-size: 16px;
        padding: 15px;
      }
      .button {
       
        padding: 15px !important;
        font-size: 18px !important;
        display: block;
      }
    }
  </style>
</head>
<body>
  <div class='email-container'>
    <div class='header-container'>
      <div class='header'>API KEY CHANGED</div>
    </div>
    
    <p>Dear " . $user["username"] . ",</p>
    <p>We would like to inform you that your <strong>API key</strong> has been successfully updated.</p>
    
    <div class='warning'>
      <p><strong>Alert:</strong> If this change was not made by you, we strongly recommend that you immediately update your account password and generate a new <strong>API key</strong> to secure your account.</p>
    </div>
    
    
    <p>If this change was made by you, no further action is required.</p>
     <p style='margin-top: 20px;'>
       <a href='" . site_url() . "tickets/' class='button'>Contact Support</a>
    </p>
    <p>Thank you for your attention to this matter.</p>

    <br>
    <p>Best regards,</p>
    <p>{$site_name} Team</p>
  </div>
</body>
</html>";
// 
// 
        $site_name = $settings["site_name"];
        $to = $user["email"]; 
$from = $settings["smtp_user"]; 
$fromName = $settings["site_seo"]; 
$subject = "Important : Your API Key Has Been Updated";
$headers = "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 
$headers .= 'From: '.$fromName.'<'.$from.'>' . "\r\n"; 
$headers .= 'Cc: '.$from . "\r\n"; 
$headers .= 'Bcc: '.$from . "\r\n"; 
 if(mail($to, $subject, $htmlContent, $headers)){ 
}else{ 
     } 
} 
      $conn->commit();
      $success    = 1;
      $successText= "API key has been generated: $apikey";

    else:
      $conn->rollBack();
      $error    = 1;
      $errorText= "Api key has not changed, Try again later!";

    endif;
  
}elseif( route(1) == "change_lang" && $_POST ){
    $lang     = $_POST["lang"];
    $update = $conn->prepare("UPDATE clients SET lang=:lang WHERE client_id=:id ");
    $update = $update->execute(array("id"=>$user["client_id"],"lang"=>$lang ));
    header("Location:".site_url('account'));
}elseif( route(1) == "currency" && $_POST ){
$conn->beginTransaction();
    $currency    = $_POST["currency"];
    $update = $conn->prepare("UPDATE clients SET currency=:type WHERE client_id=:id ");
    $update = $update->execute(array("id"=>$user["client_id"],"type"=>$currency ));
    
    header("Location:".site_url('account'));
}elseif( route(1) == "change_email" && $_POST ){
    $new_email = filter_var($_POST['new_email'], FILTER_VALIDATE_EMAIL); // Validate email format

    if (!$new_email) {
        // Invalid email format
        $error = 1;
        $errorText = "Invalid email address provided.";
    } else {
        // Check if email already exists in the database
        $check = $conn->prepare("SELECT COUNT(*) FROM clients WHERE email=:email");
        $check->execute(['email' => $new_email]);
        if ($check->fetchColumn() > 0) {
            // Email already in use
            $error = 1;
            $errorText = "This email is already in use.";
        } else {
            // Get old email before changing
            $old_email = $user["email"];
            
            // Update email in the database
            $update = $conn->prepare("UPDATE clients SET email=:email WHERE client_id=:id");
            $update_success = $update->execute(['email' => $new_email, 'id' => $user["client_id"]]);

            if ($update_success) {
                // Log the change in client report
                $log = $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date");
                $log->execute([
                    "c_id" => $user["client_id"],
                    "action" => "User email has been changed to $new_email",
                    "ip" => GetIP(),
                    "date" => date("Y-m-d H:i:s")
                ]);

                // Send a notification email to the new email address
                $site_name = $settings["site_name"];
                $from = $settings["smtp_user"];
                $fromName = $settings["site_seo"];
                $subject = "Your Email Address Has Been Updated";
              $htmlContent = "<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Email Change Notification</title>
  <style>
    /* Basic email styling */
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f4f4f4;
      color: #333;
      text-align: center;
    }
    .email-container {
      width: 100%;
      max-width: 600px;
      margin: 20px auto;
      background-color: #ffffff;
      padding: 30px;
      box-sizing: border-box;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
      border-radius: 8px;
    }
    
    /* Full-width header */
    .header-container {
      background-color: #007bff;
      padding: 20px;
      margin: -30px -30px 20px -30px; /* Extends full width */
      text-align: center;
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
    }
    .header {
      color: white;
      font-size: 22px;
      font-weight: bold;
    }
    
    p {
      font-size: 16px;
      line-height: 1.6;
      padding: 5px 10px;
      text-align: center;
    }
    a {
      color: #007bff;
      text-decoration: none;
    }
    a:hover {
      text-decoration: underline;
    }

    /* Warning Box */
    .warning {
      background-color: #f8d7da;
      border: 2px solid #f5c6cb;
      color: #721c24;
      padding: 20px;
      margin-top: 20px;
      border-radius: 8px;
      font-size: 18px;
      font-weight: bold;
      text-align: center;
    }

    /* Button */
    .button {
      background-color: #007bff;
      color: white;
      text-decoration: none;
      padding: 12px 25px;
      border-radius: 5px;
      display: inline-block;
      font-size: 16px;
      text-align: center;
      margin-top: 20px;
      font-weight: bold;
    }
    .button:hover {
      background-color: #0056b3;
    }

    /* Mobile responsiveness */
    @media only screen and (max-width: 600px) {
      .email-container {
        padding: 20px;
      }
      .header-container {
        padding: 15px;
      }
      .header {
        font-size: 20px;
      }
      .warning {
        font-size: 16px;
        padding: 15px;
      }
      .button {
       
        padding: 15px !important;
        font-size: 18px !important;
        display: block;
      }
    }
  </style>
</head>
<body>
  <div class='email-container'>
    <div class='header-container'>
      <div class='header'>Email Changed</div>
    </div>
    
    <p><strong>Hello {$user['username']},</strong></p>
    <p>We want to let you know that your email address has been changed.</p>
    
    <p><strong>Old Email:</strong> {$old_email}</p>
    <p><strong>New Email:</strong> {$new_email}</p>

    <p>If you made this change, no further action is needed.</p>

    <div class='warning'>
      <p><strong>IMPORTANT:</strong> If you did NOT make this change, please contact us immediately to secure your account.</p>
    </div>

    <p style='margin-top: 20px;'>
       <a href='" . site_url() . "tickets/' class='button'>Contact Support</a>
    </p>

    <p>Thank you for using <strong>{$site_name}</strong>.</p>
    
    <br>
    <p><strong>Best regards,</strong><br>
    <span style='color: #007bff; font-weight: bold;'>{$site_name} Team</span></p>
  </div>
</body>
</html>";


                 $site_name = $settings["site_name"];
                $headers = "MIME-Version: 1.0" . "\r\n";
                $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                $headers .= "From: {$fromName} <{$from}>" . "\r\n";

                if (!mail($new_email, $subject, $htmlContent, $headers)) {
                    // Failed to send email to the new address
                    $error = 1;
                    $errorText = "Email change was successful, but we were unable to send the notification to your new email.";
                }

                // Send a notification email to the old email address
                $subjectOld = "Important: Your Email Address Has Been Changed";
             $htmlContentOld = "<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Email Change Notification</title>
  <style>
    /* Basic email styling */
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f4f4f4;
      color: #333;
      text-align: center;
    }
    .email-container {
      width: 100%;
      max-width: 600px;
      margin: 20px auto;
      background-color: #ffffff;
      padding: 30px;
      box-sizing: border-box;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
      border-radius: 8px;
    }
    
    /* Full-width header */
    .header-container {
      background-color: #007bff;
      padding: 20px;
      margin: -30px -30px 20px -30px; /* Extends full width */
      text-align: center;
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
    }
    .header {
      color: white;
      font-size: 22px;
      font-weight: bold;
    }
    
    p {
      font-size: 16px;
      line-height: 1.6;
      padding: 5px 10px;
      text-align: center;
    }
    a {
      color: #007bff;
      text-decoration: none;
    }
    a:hover {
      text-decoration: underline;
    }

    /* Warning Box */
    .warning {
      background-color: #f8d7da;
      border: 2px solid #f5c6cb;
      color: #721c24;
      padding: 20px;
      margin-top: 20px;
      border-radius: 8px;
      font-size: 18px;
      font-weight: bold;
      text-align: center;
    }

    /* Button */
    .button {
      background-color: #007bff;
      color: white;
      text-decoration: none;
      padding: 12px 25px;
      border-radius: 5px;
      display: inline-block;
      font-size: 16px;
      text-align: center;
      margin-top: 20px;
      font-weight: bold;
    }
    .button:hover {
      background-color: #0056b3;
    }

    /* Mobile responsiveness */
    @media only screen and (max-width: 600px) {
      .email-container {
        padding: 20px;
      }
      .header-container {
        padding: 15px;
      }
      .header {
        font-size: 20px;
      }
      .warning {
        font-size: 16px;
        padding: 15px;
      }
      .button {
        
        padding: 15px !important;
        font-size: 18px !important;
        display: block;
      }
    }
  </style>
</head>
<body>
  <div class='email-container'>
    <div class='header-container'>
      <div class='header'>Email Changed</div>
    </div>
    
    <p><strong>Hello {$user['username']},</strong></p>
    <p>We want to let you know that your email address has been changed.</p>
    
    <p><strong>Old Email:</strong> {$old_email}</p>
    <p><strong>New Email:</strong> {$new_email}</p>

    <p>If you made this change, no further action is needed.</p>

    <div class='warning'>
      <p><strong>IMPORTANT:</strong> If you did NOT make this change, please contact us immediately to secure your account.</p>
    </div>

    <p style='margin-top: 20px;'>
       <a href='" . site_url() . "tickets/' class='button'>Contact Support</a>
    </p>

    <p>Thank you for using <strong>{$site_name}</strong>.</p>
    
    <br>
    <p><strong>Best regards,</strong><br>
    <span style='color: #007bff; font-weight: bold;'>{$site_name} Team</span></p>
  </div>
</body>
</html>";

                $headersOld = "MIME-Version: 1.0" . "\r\n";
                $headersOld .= "Content-type:text/html;charset=UTF-8" . "\r\n";
                $headersOld .= "From: {$fromName} <{$from}>" . "\r\n";

                if (mail($old_email, $subjectOld, $htmlContentOld, $headersOld)) {
                    // Successfully sent to old email
                    $success = 1;
                    $successText = "Your email has been updated successfully, and a notification has been sent to both your new and old email addresses.";
                } else {
                    // Failed to send email to the old address
                    $success = 1; // Email change was successful
                    $successText = "Your email has been updated successfully, but we were unable to send a notification to your old email.";
                }

            } else {
                // Database update failed
                $error = 1;
                $errorText = "Unable to update email. Please try again later.";
            }
        }
    }
}

elseif( route(1) == "timezone" && $_POST ){


    $timezone = $_POST["timezone"]; 
    $timezone = doubleval($timezone);
    $update   = $conn->prepare("UPDATE clients SET timezone=:timezone WHERE client_id=:id ");
    $update   = $update->execute(array("id"=>$user["client_id"],"timezone"=>$timezone ));
    header("Location:".site_url('account'));
}elseif( route(0) == "account" && $_POST ){

$pass     = $_POST["current_password"];
$new_pass = $_POST["password"];
$new_again= $_POST["confirm_password"];

if( !userdata_check('password', md5($pass) ) ){
    $error    = 1;
    $errorText= $languageArray["error.account.password.notmach"];
} elseif( strlen($new_pass) < 8 ){
    $error    = 1;
    $errorText= $languageArray["error.account.password.length"];
} elseif( $new_pass != $new_again ){
    $error    = 1;
    $errorText= $languageArray["error.account.passwords.notmach"];
} else {
    $conn->beginTransaction();
    
    $insert = $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date");
    $insert = $insert->execute(array(
        "c_id"   => $user["client_id"],
        "action" => "User password has been changed",
        "ip"     => GetIP(),
        "date"   => date("Y-m-d H:i:s")
    ));

    $update = $conn->prepare("UPDATE clients SET password=:pass WHERE client_id=:id");
    $update = $update->execute(array(
        "id"   => $user["client_id"],
        "pass" => md5($new_pass)
    ));

    if( $update && $insert ):
        $_SESSION["msmbilisim_userpass"] = md5($new_pass);
        $conn->commit();
        
        // Site settings for email
        $site_name = $settings["site_name"];
        $from      = $settings["smtp_user"];
        $fromName  = $settings["site_seo"];

        // Send email notification
        $to      = $user['email'];
        $subject = "Password Changed - {$site_name}";
        $headers = "MIME-Version: 1.0" . "\r\n";
        $headers .= "Content-Type: text/html; charset=UTF-8" . "\r\n";
        $headers .= "From: {$fromName} <{$from}>" . "\r\n";
       
$emailContent = "<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Password Change Notification</title>
  <style>
    /* Basic email styling */
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f4f4f4;
      color: #333;
      text-align: center;
    }
    .email-container {
      width: 100%;
      max-width: 600px;
      margin: 20px auto;
      background-color: #ffffff;
      padding: 30px;
      box-sizing: border-box;
      box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
      border-radius: 8px;
    }
    
    /* Full-width header */
    .header-container {
      background-color: #007bff;
      padding: 20px;
      margin: -30px -30px 20px -30px; /* Extends full width */
      text-align: center;
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
    }
    .header {
      color: white;
      font-size: 22px;
      font-weight: bold;
    }
    
    p {
      font-size: 16px;
      line-height: 1.6;
      padding: 5px 10px;
      text-align: center;
    }
    a {
      color: #007bff;
      text-decoration: none;
    }
    a:hover {
      text-decoration: underline;
    }

    /* Warning Box */
    .warning {
      background-color: #f8d7da;
      border: 2px solid #f5c6cb;
      color: #721c24;
      padding: 20px;
      margin-top: 20px;
      border-radius: 8px;
      font-size: 18px;
      font-weight: bold;
      text-align: center;
    }

    /* Button */
    .button {
      background-color: #007bff;
      color: white;
      text-decoration: none;
      padding: 12px 25px;
      border-radius: 5px;
      display: inline-block;
      font-size: 16px;
      text-align: center;
      margin-top: 20px;
      font-weight: bold;
    }
    .button:hover {
      background-color: #0056b3;
    }

    /* Mobile responsiveness */
    @media only screen and (max-width: 600px) {
      .email-container {
        padding: 20px;
      }
      .header-container {
        padding: 15px;
      }
      .header {
        font-size: 20px;
      }
      .warning {
        font-size: 16px;
        padding: 15px;
      }
      .button {
       
        padding: 15px !important;
        font-size: 18px !important;
        display: block;
      }
    }
  </style>
</head>
<body>
  <div class='email-container'>
    <div class='header-container'>
      <div class='header'>Password Changed</div>
    </div>
    
    <p><strong>Hello {$user['username']},</strong></p>
    <p>Your password has been successfully changed.</p>

    <p>If you made this change, no further action is needed.</p>

    <div class='warning'>
      <p><strong>IMPORTANT:</strong> If you did NOT change your password, please contact us immediately to secure your account.</p>
    </div>

    <p style='margin-top: 20px;'>
       <a href='" . site_url() . "tickets/' class='button'>Contact Support</a>
    </p>

    <p>Thank you for using <strong>{$site_name}</strong>.</p>
    
    <br>
    <p><strong>Best regards,</strong><br>
    <span style='color: #007bff; font-weight: bold;'>{$site_name} Team</span></p>
  </div>
</body>
</html>";

        mail($to, $subject, $emailContent, $headers);

        $success    = 1;
        $successText= $languageArray["error.account.password.success"];
    else:
        $conn->rollBack();
        $error    = 1;
        $errorText= $languageArray["error.account.password.fail"];
    endif;
}


}
