<?php
namespace App\Helpers;

use Postal;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;
use Request;
// use App\Models\LogActivity as LogActivityModel;
use carbon\carbon;




use App\Models\{
   Testresult,
   Classes,
   School,
   Section,
   Sms_cdr,
   User,
   Users_admission
};

class Frontend
{

   public static function sendMailPostal($to, $subject, $html,$attach)
   {

     $client = new Postal\Client('https://mail.balancepost.in', 'b1rzRaA4KLB9NYSjuoJkFXZj');
     

     // Create a new message
      //   $message = new Postal\SendMessage($client);

      $message = new Postal\Send\Message();

     // Add some recipients
     $message->to($to);
     //$message->to('mail@globalexcell.co.in');
     //$message->cc('abhishek@globalexcell.co.in');
     //$message->bcc('secret@awesomeapp.com');

     // Specify who the message should be from. This must be from a verified domain
     // on your mail server.
     $message->from('test@edukrypt.in');

     // Set the subject
     $message->subject($subject);

     // Set the content for the e-mail
     //$message->plainBody('Hello world!');
     $message->htmlBody($html);

     // Add any custom headers
     //$message->header('X-PHP-Test', 'value');

     // Attach any files
     //$message->attach($attach);

     // Send the message and get the result
   //   $result = $message->send();
     $result = $client->send->message($message);
   //   dd($result);

     return $result;
   }

   public static function sendSalaryReport($to, $subject, $html, $attach = null)
   {
      $client = new Postal\Client('https://postal.balancepost.in', 'b1rzRaA4KLB9NYSjuoJkFXZj');
      $message = new Postal\Send\Message();

      // Basic message setup
      $message->to($to);
      $message->from('test@edukrypt.in');
      $message->subject($subject);
      $message->htmlBody($html);
      $result = $client->send->message($message);
   //  dd($result);

     return $result;

      // // Handle file attachment
      // if ($attach) {
      //    try {
      //          if (is_string($attach) && file_exists($attach)) {
      //             // Handle file path
      //             $message->attach([
      //                'name' => basename($attach),
      //                'data' => base64_encode(file_get_contents($attach)),
      //                'content_type' => self::getMimeType($attach)
      //             ]);
      //          } elseif ($attach instanceof \Illuminate\Http\UploadedFile) {
      //             // Handle Laravel uploaded file
      //             $message->attach([
      //                'name' => $attach->getClientOriginalName(),
      //                'data' => base64_encode(file_get_contents($attach->getRealPath())),
      //                'content_type' => $attach->getMimeType()
      //             ]);
      //          }
      //    } catch (\Exception $e) {
      //          \Log::error("Attachment failed: " . $e->getMessage());
      //          // Continue without attachment rather than fail entire email
      //    }
      // }

      // // Send the message
      // try {
      //    $result = $client->send->message($message);
      //    return $result;
      // } catch (\Exception $e) {
      //    throw new \Exception("Failed to send email: " . $e->getMessage());
      // }
   }

   protected static function getMimeType($filePath)
   {
      $extension = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
      
      $mimeTypes = [
         'pdf' => 'application/pdf',
         'doc' => 'application/msword',
         'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
         'xls' => 'application/vnd.ms-excel',
         'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
         'csv' => 'text/csv'
      ];
      
      return $mimeTypes[$extension] ?? mime_content_type($filePath) ?: 'application/octet-stream';
   }



   public static function numberToWord($num = '')
   {
      $num = (string) ((int) $num);
      if ((int) ($num) && ctype_digit($num)) {
         $words = array();
         $num = str_replace(array(',', ' '), '', trim($num));
         $list1 = array(
            '',
            'one',
            'two',
            'three',
            'four',
            'five',
            'six',
            'seven',
            'eight',
            'nine',
            'ten',
            'eleven',
            'twelve',
            'thirteen',
            'fourteen',
            'fifteen',
            'sixteen',
            'seventeen',
            'eighteen',
            'nineteen'
         );
         $list2 = array(
            '',
            'ten',
            'twenty',
            'thirty',
            'forty',
            'fifty',
            'sixty',
            'seventy',
            'eighty',
            'ninety',
            'hundred'
         );
         $list3 = array(
            '',
            'thousand',
            'million',
            'billion',
            'trillion',
            'quadrillion',
            'quintillion',
            'sextillion',
            'septillion',
            'octillion',
            'nonillion',
            'decillion',
            'undecillion',
            'duodecillion',
            'tredecillion',
            'quattuordecillion',
            'quindecillion',
            'sexdecillion',
            'septendecillion',
            'octodecillion',
            'novemdecillion',
            'vigintillion'
         );
         $num_length = strlen($num);
         $levels = (int) (($num_length + 2) / 3);
         $max_length = $levels * 3;
         $num = substr('00' . $num, -$max_length);
         $num_levels = str_split($num, 3);
         foreach ($num_levels as $num_part) {
            $levels--;
            $hundreds = (int) ($num_part / 100);
            $hundreds = ($hundreds ? ' ' . $list1[$hundreds] . ' Hundred' . ($hundreds == 1 ? '' : 's') . ' ' : '');
            $tens = (int) ($num_part % 100);
            $singles = '';
            if ($tens < 20) {
               $tens = ($tens ? ' ' . $list1[$tens] . ' ' : '');
            } else {
               $tens = (int) ($tens / 10);
               $tens = ' ' . $list2[$tens] . ' ';
               $singles = (int) ($num_part % 10);
               $singles = ' ' . $list1[$singles] . ' ';
            }
            $words[] = $hundreds . $tens . $singles . (($levels && (int) ($num_part)) ? ' ' . $list3[$levels] . ' ' : '');
         }
         $commas = count($words);
         if ($commas > 1) {
            $commas = $commas - 1;
         }
         $words = implode(', ', $words);
         $words = trim(str_replace(' ,', ',', ucwords($words)), ', ');
         if ($commas) {
            $words = str_replace(',', ' and', $words);
         }
         return $words;
      } else if (!((int) $num)) {
         return 'Zero';
      }
      return '';
   }

   public static function getTotalTest($admission_id, $testcode)
   {
      $res = Testresult::where(['users_admission_id' => $admission_id, 'testcode' => $testcode])->where('obtained_marks','!=','N')->first();
      return $res->obtained_marks ?? '---';
   }

   public static function getUserMarks($admission_id, $testcode)
   {
      $res = Testresult::where(['users_admission_id' => $admission_id, 'testcode' => $testcode])->first();
      return $res->obtained_marks ?? '---';
   }
   public static function getUserTotalMarks($admission_id, $testcode)
   {
      $res = Testresult::where(['users_admission_id' => $admission_id, 'testcode' => $testcode])->where('obtained_marks','!=','N')->where('obtained_marks','!=','A')->first();
      return $res->max_marks ?? '---';
   }
   public static function getUserAbsent($admission_id, $testcode)
   {
      $res = Testresult::where(['users_admission_id' => $admission_id, 'testcode' => $testcode, 'obtained_marks' => 'A'])->count();
      return $res ?? '---';
   }
   public static function getUserPresent($admission_id, $testcode)
   {
      $res = Testresult::where(['users_admission_id' => $admission_id, 'testcode' => $testcode])
         ->where('obtained_marks', '!=', 0.00)
         ->first();
      return $res ?? '---';
   }
   public static function getClass($class_id)
   {
      $res = Classes::where(['id' => $class_id])->first('class');
      return $res;
   }
   public static function getSection($section_id)
   {
      $res = Section::where(['id' => $section_id])->first('section');
      return $res;
   }
   // Schools
   public static function get_schools()
   {
      $schools = School::get();
      $_schools = array();
      foreach ($schools as $school) {
         if (Auth::user()->can(strtolower($school->code))) {
            array_push($_schools, strtolower($school->code));
         }
      }
      return $_schools;
   }

   // MARKS SMS API ========================
   public static function send_marks_sms($user_id, $date, $ob_marks, $max_marks, $highest_marks)
   {
      $carbon = new Carbon($date);
      $date = $carbon->format('Y-m-d');
      $user_admission = Users_admission::where('id', $user_id)->first();
      if (!empty($user_admission)) {
         // Send SMS When User Absent
         $user = User::where('user_unique_id', $user_admission->user_unique_id)->first();
         $parent = $user->guardian()->first();
         if (!empty($parent)) {
            $phone = $user->guardian()->first()->phone;
            $school = $user->school()->first();
            $branch = $school->school;

            $name = $user_admission->first_name . ' ' . $user_admission->last_name;
            // Start
            $message_content = urlencode("$name got $ob_marks marks out of $max_marks and highest marks is $highest_marks dated on $date Paras Institute $branch");
            $smsLoad = array(
               "username" => "paraserp",
               "password" => "paraserp",
               "from" => "PICHSR",
               "pe_id" => "1701158079503322375",
               "template_id" => "1707168905104451631",
               "to" => ["$phone"],
               "text" => $message_content,
               "coding" => "0"
            );

            $curl = curl_init();
            curl_setopt_array(
               $curl,
               array(
                  CURLOPT_URL => 'https://49.50.67.32/smsapi/jsonapi.jsp',
                  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($smsLoad),
                  CURLOPT_HTTPHEADER => array(
                     'Content-Type: application/json'
                  ),
               )
            );

            $response = curl_exec($curl);
            curl_close($curl);
            $header = json_decode($response);

            // failed =================================
            if (isset($header->Error->ErrorCode)) {
               $resPonse = array(
                  "status" => false,
                  "code" => 204,
                  "message" => "Something wen wrong, please try again!",
               );
               echo json_encode($resPonse);
               $log = array(
                  'to' => $phone,
                  'text' => urldecode($message_content),
                  'status' => 0,
                  'sender_id' => 'PICHSR',
                  'template_id' => '1707168905104451631',
                  'created_at' => date('Y-m-d H:i:s')
               );
               Sms_cdr::create($log);
               exit;
            }

            // success ====================
            $log = array(
               'to' => $phone,
               'text' => urldecode($message_content),
               'status' => 1,
               'message_id' => $header->data->msgid,
               'sender_id' => 'PICHSR',
               'template_id' => '1707168905104451631',
               'created_at' => date('Y-m-d H:i:s')
            );
            Sms_cdr::create($log);
            return true;
            // End
         }
      }
   }
   // ===================================

   public static function send_absent_sms($mobile, $branch, $date)
   {
      $message_content = urlencode("Your Son/Daughter is absent on $date Paras Institute $branch");
      $smsLoad = array(
         "username" => "paraserp",
         "password" => "paraserp",
         "from" => "PICHSR",
         "pe_id" => "1701158079503322375",
         "template_id" => "1707168905081731755",
         "to" => ["$mobile"],
         "text" => $message_content,
         "coding" => "0"
      );

      $curl = curl_init();
      curl_setopt_array(
         $curl,
         array(
            CURLOPT_URL => 'https://49.50.67.32/smsapi/jsonapi.jsp',
            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($smsLoad),
            CURLOPT_HTTPHEADER => array(
               'Content-Type: application/json'
            ),
         )
      );

      $response = curl_exec($curl);
      curl_close($curl);
      $header = json_decode($response);

      // failed =================================
      if (isset($header->Error->ErrorCode)) {
         $resPonse = array(
            "status" => false,
            "code" => 204,
            "message" => "Something wen wrong, please try again!",
         );
         echo json_encode($resPonse);
         $log = array(
            'to' => $mobile,
            'text' => urldecode($message_content),
            'status' => 0,
            'sender_id' => 'PICHSR',
            'template_id' => '1707168905081731755',
            'created_at' => date('Y-m-d H:i:s')
         );
         Sms_cdr::create($log);
         exit;
      }

      // success ====================
      $log = array(
         'to' => $mobile,
         'text' => urldecode($message_content),
         'status' => 1,
         'message_id' => $header->data->msgid,
         'sender_id' => 'PICHSR',
         'template_id' => '1707168905081731755',
         'created_at' => date('Y-m-d H:i:s')
      );
      Sms_cdr::create($log);
      return true;
   }

   public static function getSingledata($table,$where)
	{

		// dd($where);
		$getdata = DB::table($table)
				->where($where)

				->first();
				// dd($session_total_chips);
				return $getdata;
	}




	//  public function getClass($school_id)
	//  {
	// 	// $class =
	//  }

}