<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\EmailSmsType;
use App\EmailSms;
use App\CustomerProperty;
use App\EmailLog;
 
use App\Http\Controllers\SmsController;
use App\Mail\SendDueAmountMail;
use App\Receipt;
use App\SmtpSetting;
use DB;
class EmailSmsController extends Controller
{
    //
    public function index(){

       $email_sms_types= EmailSmsType::all();
       return view('Setting.emailsms.index',compact('email_sms_types'));
    }
    public function viewType($id)
    {
       $email_sms_type= EmailSmsType::where('id', $id)->first();
        return view('Setting.emailsms.viewtype',compact('email_sms_type'));

    }

    public function editDetail($id)
    {
    //     $message = __('Hi, :name, how is your :type subscription?', [
    //         'name' => "Ali", 
    //         'type' => "Qasim"
    //   ]);
        // dd( $message);
       $email_sms_detail= EmailSms::where('id', $id)->first();
        return view('Setting.emailsms.editdetail',compact('email_sms_detail'));

    }
    public function storeDetail(Request $request)
    {
        
        $this->validate($request, [
            "id" => 'required',
            "content" => "required"
           
            
        ]);
 

      $detail = EmailSms::where('id',$request->id)->first();
        $detail->content = $request->content;
        if(isset( $request->status)){
            $detail->status=1;
           
        }
        else{
            
            $detail->status=0;
        }
       
        $detail->save();
        return redirect()
        ->route('email-sms.view-type',$detail->email_sms_type_id)
        ->with([
            'message' => 'Detail Added Successfully!',
            'alert-type' => 'success'
]);


    
    }

    public function createDetail($id)
    {
      $type=  EmailSmsType::where('id', $id)->first();

     $detail=   $type->detail;
        $email = 0;
        $sms =   0;

     if(!empty($detail)){
      $email_data=      $detail->where('content_type', EmailSms::content_type_email)->first();
   $sms_data  =       $detail->where('content_type', EmailSms::content_type_sms)->first();
   
   if(empty($email_data)){
                $email = 1;
   }
      if(empty($sms_data)){
                $sms = 1;
   }
     }
if( $email  == 0 &&  $sms == 0){
    return redirect()
    ->route('email-sms.view-type',$type->id)
    ->with([
        'message' => 'Both SMS and Email template already added!',
        'alert-type' => 'info'
]);

}
     return view('Setting.emailsms.add',compact('type','email','sms'));

    }

    public function storeTypeDetail(Request $request)
    {
         
        $this->validate($request, [
            "id" => 'required',
            "content" => "required",
            "contenttype"=>'required'
           
            
        ]);

       

      $detail =new EmailSms;
      $detail->email_sms_type_id = $request->id;
      $detail->content_type= $request->contenttype;
        $detail->content = $request->content;
        if(isset($request->status)){
            $detail->status=1;
        }
       
        $detail->save();
        return redirect()
        ->route('email-sms.view-type',$detail->email_sms_type_id)
        ->with([
            'message' => 'Detail Added Successfully!',
            'alert-type' => 'success'
]);
    
    }






    public function testDue(){
        $allStatements = CustomerProperty::where('status',CustomerProperty::approved)->orderBy('created_at', 'desc')->where([['is_deleted', false]])
        ->take(5)
        ->get();

        $allStatements = collect($allStatements)->filter(function ($statement) {
            return DB::table('customer_statements')
                ->where('customer_property_id', $statement->id) // replace 'id' with your statement ID column name
                ->havingRaw('SUM(CASE WHEN customer_statements.due_date < ? THEN customer_statements.balance ELSE 0 END) > 0', [\Carbon\Carbon::today()])
                ->exists();
        });
     
      dd($allStatements);
        foreach ($allStatements as $allStatement) {


            $type =   EmailSmsType::where('name', 'like', 'Over Due Amount')->first();
            if (!empty($type)) {


                $receivedAmt = 0;
                
                    $receivedAmt =  Receipt::where('customer_property_id', $allStatement->id)->where('is_approved', 1)->where('is_deleted', false)->sum('amount');
              




                $detail =   $type->detail->where('content_type', EmailSms::content_type_email)->first();
                if (!empty($detail)) {
                    
                    if ($detail->status == EmailSms::status_on) {
                        $msg =  $detail->content;
                        $balance = $allStatement->net_pay -  $receivedAmt;
                        $message = __($msg, [
                            'name' => $allStatement->customer->name,
                            'receivedamount' => $receivedAmt ,
                            'unitnumber' => $allStatement->inventory->unit_number,
                            'balance' =>$balance,
                            'membership' =>  $allStatement->membership_no

                        ]);
                        // if ( $allStatement->customer->mobile_number ) {
                        //     SmsController::sendSMS("92" . substr( $allStatement->customer->mobile_number, 1), $message);
                        // }
                        if ( $allStatement->customer->email) {
                            $customer_email=$allStatement->customer->email;

                          
                            $smtp = SmtpSetting::where('status', 1)->first();
                            $transport = (new \Swift_SmtpTransport($smtp->smtp_host, $smtp->smtp_port))
                                ->setUsername($smtp->smtp_username)
                                ->setPassword($smtp->smtp_password);
                            $mailer = new \Swift_Mailer($transport);
                            $email = (new SendDueAmountMail($message))
                                ->subject('Due Payment')
                                ->from($smtp->from_email, $smtp->from_name)
                                ->to($customer_email)
                                ->view('emails.dueamount');
                            $email_message = $email->render();
                            $swiftMessage = (new \Swift_Message())
                                ->setSubject('Due Payment')
                                ->setFrom($smtp->from_email, $smtp->from_name)
                                ->setTo($customer_email)
                                ->setBody($email_message, 'text/html');
                            $response = $mailer->send($swiftMessage);
                            $email_log =  new EmailLog();
                            $email_log->smpt_setting_id = $smtp->id;
                            $email_log->receiver_email = $customer_email;
                            $email_log->content = $message;
                            $email_log->title = 'Due Payment';
                            $email_log->mailable_class = 'new SendDueAmountMail';
                            $email_log->mail_view = 'emails.dueamount';

                            if ($response) {

                                $email_log->status = 1;
                            } else {
                                $email_log->status = 1;
                            }
                            $email_log->save();
                        }
                    }
                }
                $detail2 =   $type->detail->where('content_type', EmailSms::content_type_sms)->first();
                if (!empty($detail2)){
                    if ($detail2->status == EmailSms::status_on) {
                        $balance = $allStatement->net_pay -  $receivedAmt;

                        $msg =  $detail2->content;
                        $message = __($msg, [
                            'name' => $allStatement->customer->name,
                            'receivedamount' => $receivedAmt ,
                            'unitnumber' => $allStatement->inventory->unit_number,
                            'balance' =>  $balance ,
                            'membership' =>  $allStatement->membership_no

                        ]);
                         if ( $allStatement->customer->mobile_number ) {
                            SmsController::sendSMS("92" . substr( $allStatement->customer->mobile_number, 1), $message);
                        }
                       
                    }
                }
            }



           
             
        }
        dd('done');
    }

}
