<?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"] )); 


// confir mail


$message = "
<!DOCTYPE html>
<html lang='en'>
<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Confirm Your Email Address</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            padding: 20px;
            margin: 0;
            color: #333;
        }
        .email-container {
            background-color: #ffffff;
            padding: 30px;
            border-radius: 8px;
            max-width: 600px;
            margin: 0 auto;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .btn-container {
            text-align: center;
            margin-top: 20px;
        }
        .btn {
            display: inline-block;
            background-color: #007bff;
            color: white;
            text-decoration: none;
            padding: 12px 20px;
            font-size: 16px;
            border-radius: 5px;
        }
        .btn:hover {
            background-color: #0056b3;
        }
        .alternative-link {
            display: block;
            margin-top: 15px;
            font-size: 14px;
            color: #007bff;
            text-decoration: none;
        }
        .alternative-link:hover {
            text-decoration: underline;
        }
        /* Responsive Design */
        @media only screen and (max-width: 600px) {
            .email-container {
                padding: 20px;
                width: 100%;
            }
            .btn {
                width: 100%;
                text-align: center;
                padding: 10px;
                font-size: 18px; /* Increase font size for better readability on mobile */
            }
            .alternative-link {
                font-size: 16px; /* Slightly larger font for better readability on mobile */
            }
        }
    </style>
</head>
<body>
    <table role='presentation' width='100%' cellspacing='0' cellpadding='0' style='background-color: #f4f4f4; padding: 20px;'>
        <tr>
            <td align='center'>
                <table role='presentation' class='email-container' cellspacing='0' cellpadding='0' width='100%'>
                    <tr>
                        <td style='padding: 30px; background-color: #ffffff;'>
                            <p>Dear User,</p>
                            <p>To complete the registration process, please confirm your email address by clicking the link below:</p>
                            
                            <!-- Button container to center the button -->
                            <div class='btn-container'>
                                <a href='" . site_url() . "confirm_email/activate/$code' class='btn'>Confirm Your Email</a>
                            </div>

                            <!-- Alternative link if the user can't see the button -->
                            <p>If the button doesn't work, you can copy and paste the following link into your browser:</p>
                            <p><a href='" . site_url() . "confirm_email/activate/$code' class='alternative-link'>" . site_url() . "confirm_email/activate/$code</a></p>

                            <p>If you did not request this, please disregard this message.</p>
                            <br>
                            <p>Best regards,<br>Our Team</p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>";



$site_name = site_url();
$to = $user['email'];
$site_name = $settings["site_name"];
$from = $settings["smtp_user"]; 
$subject = 'Account Confirmation';
$headers = "MIME-Version: 1.0" . "\r\n"; 
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 
$headers .= 'From: ' . $site_name . ' SMM <' . $from . ">\r\n";
$headers .= 'Cc: '.$from . "\r\n"; 
$headers .= 'Bcc: '.$from . "\r\n"; 
$send = mail($to, $subject, $message, $headers);


        


            if( $send):


      $success    = 1;
        $successText= "A confirmation email has been sent";
echo '<script>setTimeout(function(){window.location="'.site_url().'"},2000)</script>';
   
        
        else:
          $error    = 1;
          $errorText= "Failed";
          
        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'];

// confirm mail 

$msg = "
<!DOCTYPE html>
<html lang='en'>
<head>
  <meta charset='UTF-8'>
  <meta name='viewport' content='width=device-width, initial-scale=1.0'>
  <title>Email Confirmation</title>
  <style>
    /* Basic styling for the email */
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
      background-color: #f4f4f4;
    }
    table {
      width: 100%;
      max-width: 600px;
      margin: 0 auto;
      background-color: #ffffff;
    }
    td {
      padding: 15px;
      text-align: left; /* Left-align text */
    }
    .button-container {
      text-align: center; /* Center-align the button */
      padding: 15px 0;
    }
    .button {
      background-color: #007BFF; /* Blue button */
      color: white;
      text-decoration: none;
      padding: 15px 30px;
      border-radius: 5px;
      display: inline-block;
      font-size: 16px;
      text-align: center;
      width: auto; /* Button width is determined by content */
      box-sizing: border-box;
    }
    .button:hover {
      background-color: #0056b3; /* Darker blue on hover */
    }
    .text-link {
      color: #007BFF; /* Blue link */
      text-decoration: none;
      font-size: 16px;
      display: block;
      margin-top: 20px;
    }
    .text-link:hover {
      text-decoration: underline;
    }

    /* Mobile responsiveness */
    @media only screen and (max-width: 600px) {
      table {
        width: 100% !important;
        padding: 10px !important; /* Adjust padding for smaller screens */
      }
      .button {
        padding: 20px !important;
        font-size: 18px !important;
        width: 100% !important; /* Ensure button takes full width */
        box-sizing: border-box;
      }
      .text-link {
        font-size: 18px !important;
        padding: 10px !important;
      }
    }

    /* Tablet responsiveness (screens between 600px - 800px) */
    @media only screen and (max-width: 800px) {
      .button {
        font-size: 18px !important;
        padding: 18px 35px !important;
      }
      .text-link {
        font-size: 18px !important;
      }
    }

    /* Desktop responsiveness */
    @media only screen and (min-width: 800px) {
      .button {
        font-size: 16px !important;
        padding: 15px 30px !important;
      }
      .text-link {
        font-size: 16px !important;
      }
    }
  </style>
</head>
<body>
  <table>
    <tr>
      <td>
        <p>Dear User,</p>
        <p>To verify your account and complete the registration process, please confirm your email address by clicking the button below:</p>
        <div class='button-container'>
          <a href='" . site_url() . "confirm_email/activate/$code' class='button'>Confirm Your Email Address</a>
        </div>
        <p>If you cannot click the button, you can also use the following link:</p>
        <a href='" . site_url() . "confirm_email/activate/$code' class='text-link'>" . site_url() . "confirm_email/activate/$code</a>
        <p>If you did not request this, please ignore this message.</p>
        <br><br>
        <p>Best regards,</p>
        <p>Our Team</p>
      </td>
    </tr>
  </table>
</body>
</html>
";





        $send = mail($newemail,"Email Confirmation",$msg);

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



      $success    = 1;
        $successText= "A confirmation email has been sent";
        echo '<script>setTimeout(function(){window.location="'.site_url().'"},2000)</script>';

        else:
          $error    = 1;
          $errorText= "Failed";
          $conn->rollBack(confirm_email);
        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= $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= $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= $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;
    $c_id       = $user["client_id"];
    $to         = 25;
    $count      = $conn->query("SELECT * FROM orders WHERE client_id='$c_id' && dripfeed='1' && subscriptions_type='2' $search ")->rowCount();
    $pageCount  = ceil($count/$to);
      if( $page > $pageCount ): $page = 1; endif;
    $where      = ($page*$to)-$to;
    $paginationArr = ["count"=>$pageCount,"current"=>$page,"next"=>$page+1,"previous"=>$page-1];

  $orders = $conn->prepare("SELECT * FROM orders INNER JOIN services WHERE services.service_id = orders.service_id && orders.dripfeed=:dripfeed && orders.subscriptions_type=:subs && orders.client_id=:c_id $search ORDER BY orders.order_id DESC LIMIT $where,$to ");
  $orders-> execute(array("c_id"=>$user["client_id"],"dripfeed"=>1,"subs"=>2 ));
  $orders = $orders->fetchAll(PDO::FETCH_ASSOC);
  $ordersList = [];

    foreach ($orders as $order) {
      $o["id"]              = $order["order_id"];
      $o["date_created"]    = date("d.m.Y H:i:s", (strtotime($order["order_create"])+$user["timezone"]) );
      $o["date_updated"]    = date("d.m.Y H:i:s", (strtotime($order["last_check"])+$user["timezone"]) );
      $o["date_expiry"]     = date("d.m.Y", strtotime($order["subscriptions_expiry"]) ); if( $o["date_expiry"] == "01.01.1970 00:00" ): $o["date_expiry"] = ""; endif;
      $o["link"]            = $order["order_url"];
      $o["service"]         = $order["service_name"];
      $o["posts"]           = $order["subscriptions_posts"];
      $o["current_count"]   = $order["subscriptions_delivery"];
      $o["quantity_min"]    = $order["subscriptions_min"];
      $o["quantity_max"]    = $order["subscriptions_max"];
      $o["delay"]           = ($order["subscriptions_delay"]/60); if( $o["delay"] == 0 ): $o["delay"] = "Gecikme yok"; endif;
      $o["status_name"]     = $languageArray["subscriptions.status.".$order["subscriptions_status"]];
      $o["status"]          = $order["subscriptions_status"];
      array_push($ordersList,$o);
    }