<?php

namespace App\Jobs;

use App\Exports\ExportDayBookReport;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class ExportDayBookReportJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $slug;
    protected $fromDate;
    protected $toDate;
    protected $userId;
    protected $filename;

    public function __construct($slug, $fromDate, $toDate, $userId, $filename)
    {
        $this->slug = $slug;
        $this->fromDate = $fromDate;
        $this->toDate   = $toDate;
        $this->userId = $userId;
        $this->filename = $filename;
    }

    public function handle()
    {
        Log::info("Daybook Excel Job started for User ID: {$this->userId}");

        try {
            $relativePath = 'excel_export/' . $this->filename;

            Excel::store(new ExportDayBookReport($this->slug, $this->fromDate, $this->toDate), $relativePath, 'public');

            DB::table('excel_exports')->insert([
                'user_id'    => $this->userId,
                'file_path'  => $relativePath,
                'file_name'  => $this->filename,
                'created_at' => now(),
            ]);

            Log::info("Daybook Excel generated and saved: {$relativePath}");
        } catch (\Exception $e) {
            Log::error("Daybook Excel export failed: " . $e->getMessage());
        }
    }
}
