<?php

namespace App\Traits;

use App\DataTables\ChimpReportDataTable;
use App\DataTables\MailApiDataTable;
use App\Tools\SendinBlueEmailService;
use App\UserEmailCampaign;
use DrewM\MailChimp\MailChimp;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Html;
use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use stdClass;
use Symfony\Component\HttpFoundation\StreamedResponse;


trait ChimpReport
{

    // ============================== SENDINBLUE ============================== //

    private $sendinblue;

    public function __construct(){
        $this->sendinblue = new SendinBlueEmailService();
    }

    public function campaignsReport(ChimpReportDataTable $sendinblue)
    {
        return $sendinblue->render('sendinblue.campaigns.reports.index');
    }

    public function campaignsAPI(MailApiDataTable $sendinblue)
    {
        return $sendinblue->render('sendinblue.campaigns.reports.index');
    }

    public function campaignsReportView(UserEmailCampaign $emailCampaign)
    {
        $user = Auth::user();
        $limit = $user->subscriptionLimits();// check for subscription limits and redirect accordingly

        if(!isset($limit))
            return redirect()->route('email.subscription.index')->withErrors("kindly choose a package here !!");


//        $report  = session()->get('sendinblue_report') ?? $this->getCampaignReport($emailCampaign->mail_campaign_id);
        $report  = $this->getCampaignReport($emailCampaign->mail_campaign_id);
        session()->put(['sendinblue_report'=>$report]);
        $report  = $this->array_to_object($report);

        return  isset($report->id) ? view('sendinblue.campaigns.reports.view',compact('report','emailCampaign')) : redirect()->back()->withErrors('CAMPAIGN RESULT COULD NOT BE FOUND');
    }


    public function campaignsReportPdf(UserEmailCampaign $emailCampaign)
    {
        try {
            $report = session()->get('sendinblue_report') ?? $this->getCampaignReport($emailCampaign->mail_campaign_id);
            $report  = $this->array_to_object($report);

            $reader = new Html();
            $spreadsheet = $reader->loadFromString( view('sendinblue.campaigns.reports.print',compact('report','emailCampaign')));

            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');

            // Set the filename for the Excel file
            $filename = 'campaign_report_' . $report->id . Str::random(7) . '.xlsx';

            // Set the storage path for the Excel file
            $path = 'public/campaignReport/' . $filename;

            // Create the directory if it doesn't exist
            Storage::makeDirectory('public/campaignReport');

            $writer->save(storage_path('app/' . $path));

        }catch (\Exception $ex)
        {
            return redirect()->back()->withErrors('Report could not be generated');
        }


        return response()->download(storage_path('app/' . $path))->deleteFileAfterSend();
    }


    public function getCampaignReport($mailCampaignId){
        $endpoint = 'get-single-campaign-email/'.$mailCampaignId;
        return $this->sendinblue->getApiCall($endpoint);
    }


    // ============================== SENDINBLUE ============================== //

    public function campaignsReportOld(ChimpReportDataTable $chimp)
    {
        return $chimp->render('chimp.reports.index');
    }

    public function campaignsAPIOld(MailApiDataTable $chimp)
    {
        return $chimp->render('chimp.reports.index');
    }

    public function campaignsReportViewOld(UserEmailCampaign $emailCampaign)
    {
        $user = Auth::user();
        $limit = $user->subscriptionLimits();// check for subscription limits and redirect accordingly

        if(!isset($limit))
            return redirect()->route('email.subscription.index')->withErrors(
                "kindly choose a package here !!"
            );


        $report  = session()->get('chimp_report') ?? $this->get_campaign_report($emailCampaign->mail_campaign_id);
        session()->put(['chimp_report'=>$report]);
        $report  = $this->array_to_object($report);
        return  isset($report->id) ? view('chimp.reports.view',compact('report','emailCampaign')) : redirect()->back()->withErrors('CAMPAIGN RESULT COULD NOT BE FOUND');
    }

    public function campaignsReportPdfOld(UserEmailCampaign $emailCampaign)
    {
        try {

        $report = session()->get('chimp_report');
        $report  = $this->array_to_object($report);


        $reader = new Html();
        $spreadsheet = $reader->loadFromString( view('chimp.reports.print',compact('report','emailCampaign')));

        $writer = IOFactory::createWriter($spreadsheet, 'Xls');
        $path = storage_path("app/public/pdf/$report->id.write.xls");
        $writer->save($path);
        }catch (\Exception $ex)
        {
            return redirect()->back()->withErrors('Report could not be generated');
        }

        return response()->download($path);


    }

}
