<?php

namespace App\Jobs;

use App\Models\User;
use App\Mail\SendReportMail;
use App\Mails\ReportTestMail;
use App\Models\Resource;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Mail;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Http\Request;

class SendReportJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    /**
     * Create a new job instance.
     */
    public $user;
    public $report;
    public $request;
    public $receiver;
    public function __construct($request, Resource $report, User $user, $receiver)
    {
        $this->user = $user;
        $this->report = $report;
        $this->request = $request;
        $this->receiver = $receiver;
    }

    /**
     * Retrieves the URL for the report.
     *
     * This method constructs the URL for the report by extracting the public URI from the `PHP_SELF` request
     * variable and appending the report's URL.
     *
     * @tag srm_schdular
     */
    private function getReportUrl()
    {
        $public_uri = explode("/index.php", $this->request["PHP_SELF"])[0];

        return "$public_uri/srm_modules/{$this->report->url}";
    }

    /**
     * Retrieves the path to the generated PDF of the report.
     *
     * This method constructs the file path for the generated PDF by removing the last segment of the report URL
     * and appending the cleaned report name with `-singlepage.pdf` to the document root.
     *
     * @tag srm_schdular
     */
    private function getReportPdf()
    {
        $reportPath = explode('/', $this->getReportUrl());

        array_pop($reportPath);

        $reportPath = implode('/', $reportPath);

        return $this->request['DOCUMENT_ROOT']. "$reportPath" . "/".str_replace(' ', '', $this->report->name).'-singlepage.pdf';
    }

    /**
     * Executes the job of sending the report via email.
     *
     * This method handles the process of generating the report's PDF file path, and then sends an email with the
     * PDF attached to the designated recipient.
     *
     * @tag srm_schdular
     */
    public function handle(): void
    {
        (new ReportTestMail($this->getReportPdf(), $this->user))
        ->setReceivcer($this->receiver)
        ->send();
    }



}
