<?php

class Backpack_Files
{
    /**
     * Constructor method.
     *
     * @param Backpack $backpack An instance of the Backpack class.
     *
     * @return void
     */
    public function __construct(private Backpack $backpack)
    {
        //
    }

    /**
     * Handles the backup process for files based on the provided schedule.
     *
     * @param array $schedule The schedule details containing backup settings and file paths.
     * @param bool  $export   Optionally determines whether the backup file should be exported to S3. Defaults to true.
     *
     * @return string Returns the path of the compressed backup file.
     */
    public function backup(array $schedule, bool $export = true)
    {
        // ray($schedule);

        $this->backpack->log("Beginning file backup for task {$schedule['id']}.");

        $file = sprintf("%s/%s_backup_%s_%s", get_option("mws_backpack_backup_path"), $this->backpack->getDomainName(), $this->backpack->slugify($schedule["name"]), Carbon\Carbon::now($this->backpack->getTimezone())->format('Y-m-d_H-i-s'));

        $compressor = new Backpack_Compress($this->backpack);
        $compressedFile = $compressor->zip($file . '.zip', $schedule["settings"]["file"]["path"], $schedule["settings"]["file"]["path_ignore"] ?? []);

        if ($export === false) {
            return $compressedFile;
        }

        // Export the file
        $this->backpack->log("Exporting file to S3.");

        try {
            // Get the site URL from WordPress
            $domain       = $this->backpack->getDomainName();
            $date         = Carbon\Carbon::now()->format('Y-m-d');
            $baseFilename = basename($compressedFile);

            $export = new Backpack_Export($this->backpack);
            $export->toS3("{$domain}/{$date}/{$baseFilename}", $compressedFile, (int) $schedule["id"]);
        } catch (\Exception $e) {
            $this->backpack->log("Failed to export file to S3. Exception: " . $e->getMessage());
        }

        $this->backpack->log("File exported to S3.");

        return $compressedFile;
    }
}
