<?php
if(!defined('BASEPATH')) {
   die('Direct access to the script is not allowed');
}

$title .= "Confirm Email";

if( $_SESSION["msmbilisim_userlogin"] != 1  || $user["client_type"] == 1  ){
  Header("Location:".site_url('logout'));
}

if( $settings["email_confirmation"] == 1 && $user["email_type"] == 1  ){
  //Header("Location:".site_url(''));
}

if( route(1) == "resend" ){
    if ($user["resend_max"] >= $settings["resend_max"]) {
        $error    = 1;
        $errorText = "Apologies, you have reached the maximum limit of " . $user["resend_max"] . " confirmation emails. No further emails can be sent at this time.";
    } else {
        $email = route(2);
        $row = $conn->prepare("SELECT * FROM clients WHERE client_id=:id");
        $row->execute(array("id" => iser["client_id"]));
        $row = $row->fetch(PDO::FETCH_ASSOC);

        $code = $user['apikey'];
        
        $max = $user["resend_max"] + 1;
        $update = $conn->prepare("UPDATE clients SET resend_max=:max WHERE client_id=:id");
        $update->execute(array("max" => $max, "id" => $user["client_id"]));
        
        // Prepare email message
$to = $user["email"]; // User's email address
$from = $settings["smtp_user"]; 
$fromName = $settings["site_seo"]; 
$replyTo = $settings["admin_mail"];
$subject = "Confirm Your Email Address - {$settings['site_name']}";
$email_message = "<html><body style='font-family: Inter, Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0;'>";
$email_message .= "<div style='max-width: 600px; margin: 20px auto; background: #ffffff; border-radius: 10px; box-shadow: 0px 0px 10px rgba(0,0,0,0.1); padding: 20px; text-align: center;'>";
$email_message .= "<div style='background: #007bff; color: #ffffff; padding: 15px; font-size: 24px; font-weight: bold; border-radius: 10px 10px 0 0;'>";
$email_message .= "{$settings['site_name']} - Email Confirmation</div>";
$email_message .= "<div style='padding: 20px; font-size: 16px; color: #333; line-height: 1.6;'>";
$email_message .= "<p>Dear User,</p>";
$email_message .= "<p>To complete the registration process, please confirm your email address by clicking the link below:</p>";
$email_message .= "<p><a href='" . site_url() . "confirm_email/activate/$code' style='font-size: 16px; color: #007bff; text-decoration: none;'>Confirm Email Address</a></p><br>";
$email_message .= "<p>If you did not request this, please disregard this message.</p>";
$email_message .= "<p>Best regards,<br><strong>{$settings['site_name']}</strong> Team</p>";
$email_message .= "</div>";
$email_message .= "<div style='margin-top: 20px; font-size: 14px; color: #777;'>";
$email_message .= "&copy; " . date("Y") . " {$settings['site_name']}. All rights reserved.";
$email_message .= "</div>";
$email_message .= "</div>";
$email_message .= "</body></html>";


// Email headers
$headers = "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 
$headers .= 'From: '.$fromName.'<'.$from.'>' . "\r\n"; 
$headers .= 'Reply-To: '.$replyTo . "\r\n";
$send = mail($to, $subject, $email_message, $headers);


        // Prepare Telegram message
        $message = "Dear User,\n\n";
        $message .= "To complete the registration process, please confirm your email address by clicking the link below:\n\n";
        $message .= site_url() . "confirm_email/activate/$code\n\n";
        $message .= "If you did not request this, please disregard this message.";

        // Send Telegram notification
        $telegramusertoken = $settings["telegramusertoken"];
        $telegram_api_url = "https://api.telegram.org/bot$telegramusertoken/sendMessage";
        
        // Prepare data for Telegram API
        $data = [
            'chat_id' => $user['chat_id'],  // Ensure this is the correct chat ID
            'text' => $message
        ];

        // Use cURL to send the message via Telegram API
        $ch = curl_init($telegram_api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_exec($ch);
        curl_close($ch);

        if($send):
            $success = 1;
            $successText = "A confirmation message has been sent via Telegram & Email";
            echo '<script>setTimeout(function(){window.location="'.site_url().'"},2000)</script>';
        else:
            $error = 1;
            $errorText = "Failed to send confirmation message via Telegram & Email";
        endif;
    }
}

if( route(1) == "activate" ){
    $code = route(2);
    $update = $conn->prepare("UPDATE clients SET email_type=:type WHERE apikey=:key ");
    $update->execute(array("type" => 2, "key" => $code));
    Header("Location:".site_url(''));
    exit();
}

if( $_POST ){
    foreach ($_POST as $key => $value) {
        $_SESSION["data"][$key] = $value;
    }

    $pass = $_POST["password"];
    $newemail = $_POST["newemail"];
    $ps = md5($pass);
    if( empty($newemail) ){
        $error = 1;
        $errorText = "Please enter a valid email";
    } elseif( empty($pass) ){
        $error = 1;
        $errorText = "Please enter your password";
    } elseif (userdata_check("email", $newemail)) {
        $error = 1;
        $errorText = "Email is already registered";
    } elseif( !userdata_check("password", $ps) ){
        $error = 1;
        $errorText = "Incorrect password";
    } else {
        $update = $conn->prepare("UPDATE clients SET email=:email, change_email=:mail WHERE client_id=:id");
        $update->execute(array("id" => $user["client_id"], "mail" => 1, "email" => $newemail));

        $row = $conn->prepare("SELECT * FROM clients WHERE email=:email ");
        $row->execute(array("email" => route(2)));
        $row = $row->fetch(PDO::FETCH_ASSOC);
        $code = $user['apikey'];
        
$to = $user["email"]; // User's email address
$from = $settings["smtp_user"]; 
$fromName = $settings["site_seo"]; 
$replyTo = $settings["admin_mail"];
$subject = "Confirm Your Email Address - {$settings['site_name']}";
$email_message = "<html><body style='font-family: Inter, Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 0;'>";
$email_message .= "<div style='max-width: 600px; margin: 20px auto; background: #ffffff; border-radius: 10px; box-shadow: 0px 0px 10px rgba(0,0,0,0.1); padding: 20px; text-align: center;'>";
$email_message .= "<div style='background: #007bff; color: #ffffff; padding: 15px; font-size: 24px; font-weight: bold; border-radius: 10px 10px 0 0;'>";
$email_message .= "{$settings['site_name']} - Email Confirmation</div>";
$email_message .= "<div style='padding: 20px; font-size: 16px; color: #333; line-height: 1.6;'>";
$email_message .= "<p>Dear User,</p>";
$email_message .= "<p>To complete the registration process, please confirm your email address by clicking the link below:</p>";
$email_message .= "<p><a href='" . site_url() . "confirm_email/activate/$code' style='font-size: 16px; color: #007bff; text-decoration: none;'>Confirm Email Address</a></p><br>";
$email_message .= "<p>If you did not request this, please disregard this message.</p>";
$email_message .= "<p>Best regards,<br><strong>{$settings['site_name']}</strong> Team</p>";
$email_message .= "</div>";
$email_message .= "<div style='margin-top: 20px; font-size: 14px; color: #777;'>";
$email_message .= "&copy; " . date("Y") . " {$settings['site_name']}. All rights reserved.";
$email_message .= "</div>";
$email_message .= "</div>";
$email_message .= "</body></html>";


// Email headers
$headers = "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 
$headers .= 'From: '.$fromName.'<'.$from.'>' . "\r\n"; 
$headers .= 'Reply-To: '.$replyTo . "\r\n";
$send = mail($to, $subject, $email_message, $headers);


        // Prepare Telegram message
        $message = "Dear User,\n\n";
        $message .= "To complete the registration process, please confirm your email address by clicking the link below:\n\n";
        $message .= site_url() . "confirm_email/activate/$code\n\n";
        $message .= "If you did not request this, please disregard this message.";

        // Send Telegram notification
        $telegramusertoken = $settings["telegramusertoken"];
        $telegram_api_url = "https://api.telegram.org/bot$telegramusertoken/sendMessage";
        
        // Prepare data for Telegram API
        $data = [
            'chat_id' => $user['chat_id'],  // Ensure this is the correct chat ID
            'text' => $message
        ];

        // Use cURL to send the message via Telegram API
        $ch = curl_init($telegram_api_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_exec($ch);
        curl_close($ch);

        $insert2 = $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date ");
        $insert2 = $insert2->execute(array("c_id" => $user["client_id"], "action" => "User updated email address from $mail to $newemail."
,"ip" => GetIP(), "date" => date("Y-m-d H:i:s") ));

        if( $update && $send):
            $success = 1;
            $successText = "A confirmation message has been sent via Telegram & Email";
            echo '<script>setTimeout(function(){window.location="'.site_url().'"},2000)</script>';
        else:
            $error = 1;
            $errorText = "Failed to send confirmation message via Telegram & Email";
            $conn->rollBack();
        endif;
    }
}

if( route(1) == "pause" ):
    $order_id = route(2);
    $row = $conn->prepare("SELECT * FROM orders WHERE order_id=:id && ( subscriptions_status=:status || subscriptions_status=:status2 ) ");
    $row->execute(array("id"=>$order_id,"status"=>"active","status2"=>"expired" ));
    if( $row->rowCount() ):
        $row = $row->fetch(PDO::FETCH_ASSOC);
        $update = $conn->prepare("UPDATE orders SET subscriptions_status=:status WHERE order_id=:id");
        $update->execute(array("id"=>$order_id,"status"=>"paused"));
        $insert = $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date ");
        $insert->execute(array("c_id"=>$user["client_id"],"action"=>"Abonelik durduruldu #".$row["order_id"],"ip"=>GetIP(),"date"=>date("Y-m-d H:i:s") ));
    endif;
    Header("Location:".site_url('subscriptions'));
    exit();
elseif( route(1) == "resume" ):
    $order_id = route(2);
    $row = $conn->prepare("SELECT * FROM orders WHERE order_id=:id && subscriptions_status=:status ");
    $row->execute(array("id"=>$order_id,"status"=>"paused"));
    if( $row->rowCount() ):
        $row = $row->fetch(PDO::FETCH_ASSOC);
        $update = $conn->prepare("UPDATE orders SET subscriptions_status=:status WHERE order_id=:id");
        $update->execute(array("id"=>$order_id,"status"=>"active"));
        $insert = $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date ");
        $insert->execute(array("c_id"=>$user["client_id"],"action"=>"Abonelik aktifleştirildi #".$row["order_id"],"ip"=>GetIP(),"date"=>date("Y-m-d H:i:s") ));
    endif;
    Header("Location:".site_url('subscriptions'));
    exit();
elseif( route(1) == "stop" ):
    $order_id = route(2);
    $row = $conn->prepare("SELECT * FROM orders WHERE order_id=:id && ( subscriptions_status=:status || subscriptions_status=:status2 ) ");
    $row->execute(array("id"=>$order_id,"status"=>"paused","status2"=>"active"));
    if( $row->rowCount() ):
        $row = $row->fetch(PDO::FETCH_ASSOC);
        $update = $conn->prepare("UPDATE orders SET subscriptions_status=:status WHERE order_id=:id");
        $update->execute(array("id"=>$order_id,"status"=>"canceled"));
        $insert = $conn->prepare("INSERT INTO client_report SET client_id=:c_id, action=:action, report_ip=:ip, report_date=:date ");
        $insert->execute(array("c_id"=>$user["client_id"],"action"=>"Abonelik iptal edildi #".$row["order_id"],"ip"=>GetIP(),"date"=>date("Y-m-d H:i:s") ));
    endif;
    Header("Location:".site_url('subscriptions'));
    exit();
endif;

$status_list  = ["all","active","completed","canceled","paused","expired"];
$search_statu = route(1); if( !route(1) ):  $route[1] = "all";  endif;

if( !in_array($search_statu,$status_list) ):
    $route[1] = "all";
endif;

if( route(2) ):
    $page = route(2);
else:
    $page = 1;
endif;
if( route(1) != "all" ): 
    $search  = "&& subscriptions_status='".route(1)."'"; 
else: 
    $search = ""; 
endif;
if( !empty($_GET["search"]) ): 
    $search .= " && ( order_url LIKE '%".$_GET["search"]."%' ||  order_id LIKE '%".$_GET["search"]."%' ) ";
endif;
?>
