<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use App;
use DB;
use PDF;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Redirect;
use App\Http\Requests;
use App\Mail\InvoiceMail;
use App\MailInvoice;
use App\User;
use App\ServerConfig;
use App\UserProduct;
use App\PaymentLink;

use App\Helpers\MailHelper as MailHelper;

use Illuminate\Support\Collection;

class MailInvoiceController extends Controller
{
  public function mail_invoice_sent()
  {
		$user_arr = User::where('verified',1)->get();
    //dd($user_arr);
    foreach($user_arr as $users)
		{
      $email = $users->email;
      $name = $users->name;
      ////check the last_inv_mail_timestamp from mail_invoice for that customer //////////////////////////
      $mail_inv_count = MailInvoice::where('customer_email',$email)->orderBy('id','desc')->count();
      $mail_inv_arr = MailInvoice::where('customer_email',$email)->orderBy('id','desc')->first();
      //dd($mail_inv_arr);
      if(isset($mail_inv_arr))
      {
        $last_inv_mail_timestamp = $mail_inv_arr->last_inv_mail_timestamp;
        $checktimestamp = $last_inv_mail_timestamp;
      }
      else
      {
          $checktimestamp = "01-11-2023";
          $checktimestamp = strtotime($checktimestamp);
      }
      //dd($checktimestamp);
      $server_config = ServerConfig::first();
      if(isset($server_config))
      {
          $api_url = $server_config->server_url;
      }            
      $data = [
                  'email' => $email,
                  'product_slugname' => 'digifile',
                  'checktimestamp' => $checktimestamp,
              ];
      /////to get the active invoices////////////////////////////////////////////////////
      $curl = curl_init();
      curl_setopt_array($curl, array(
          CURLOPT_URL => $api_url.'api/checkinvoicetimestamp',
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => true,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "POST",
          CURLOPT_POSTFIELDS => json_encode($data),
          CURLOPT_HTTPHEADER => array(
              // Set here requred headers
              "accept: */*",
              "accept-language: en-US,en;q=0.8",
              "content-type: application/json",
              "X-Authorization: I7GWTYs5RQ4dS3nokv3c9ADWCcBt8p8v8enWmOnpnUUsmBsbJmAjgxO7A6RvbwCq",     //////api key generated for get invoice
          ),
      ));
      $response = curl_exec($curl);
      //dd($response);
      $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
      $err = curl_error($curl);
      curl_close($curl);
      if ($err) 
      {
          echo "cURL Error #:" . $err;
      } 
      else 
      {
          $invoices = json_decode($response);
      }
      //dd($invoices);
      if(isset($invoices))
      {
        foreach($invoices as $invoice)
        {
            $invoice_status = $invoice->stripe_status;
            //echo "invoice_status=$invoice_status....".now().".<br>";
            if($invoice_status=="active")
            {
              //echo "test..";
              $invoice_date = $invoice->invoice_date;
              $invoice_number = $invoice->invoice_number;
              $pname = $invoice->plan_name;
              if($pname)
              {
                $pnamearr = explode("×", $pname);
                $pname_last = explode("(", $pnamearr[1]);
                $plan_name_stripe = trim($pname_last[0]);
                $paymentlinks = PaymentLink::where('slugname',$plan_name_stripe)->first();
                if(isset($paymentlinks))
                {
                  $plan_name = $paymentlinks->display_name;
                }
              }
              $currency = $invoice->currency;
              $amount = $invoice->amount;
              $invoice_pdf_list = $invoice->invoice_pdf_list;
              $current_period_start  =$invoice->current_period_start;
              $current_period_end = $invoice->current_period_end;
              $invoice_period = $current_period_start." To ".$current_period_end;
              $invoice_amount = $amount." ".$currency;
              $html = "";
              $html .= "Dear ".$name.", <br><br> Congratulations and welcome aboard! Your payment for DigiFile has been successfully processed, and we're thrilled to have you as a part of our community. <br><br> Here are the key details of your subscription: <br>";

              $html .= "Plan : ".$plan_name;
              $html .= "<br>Subscription Period : ".$invoice_period;
              $html .= "<br>Payment Amount : ".$invoice_amount;
              $html .= "<br><br>Your subscription is now active. To get started, please log in to your account at http://188.166.183.162/ffms/public/index.php/login using the credentials you previously set up.<br> If you have any questions, encounter issues accessing your account, or need assistance with anything related to DigiFile, don't hesitate to reach out to our support team at support@ffms.app. We're here to help you make the most out of your experience. <br> Thank you for choosing DigiFile. We're committed to providing you with an exceptional experience.";
              $html .= "<br><br>Best Regards, <br>Sreekanth S, <br>Director, <br>DigiFile.";
              //dd($html);
              $data= ['message' => $html, 'mailto'=>$email, 'name_data'=>'Invoice' ];
              //dd($data);
              //mailing to the registered email
              Mail::to($email)->send(new InvoiceMail($data));
              ////insert the values in mail invoice table//////////////////////////////
              $current_timestamp = strtotime(date("d-m-Y"));
              $mail_inv = new MailInvoice([
                  'customer_email'  => $email,
                  'last_inv_mail_timestamp' => $current_timestamp,
                  'status' => 1,
                  ]);
              $mail_inv->save();
              dd($mail_inv);
            } 
        }
      }
    }
   }
}
