<?php

namespace App\Http\Controllers\api;

use Exception;
use App\Traits\ExportTrait;
use App\Models\Application\Group;
use App\Exports\GroupFailureExport;
use App\Http\Controllers\Controller;
use App\Http\Requests\ExportRequest;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Excel as ExcelFormat;

class ExportController extends Controller
{
    use ExportTrait;

    private $MESSAGES = [
        'GROUPFAILURE' => 'WARNING.EXPORT_GROUPFAILURE',
        'EMPTY' => 'WARNING.EXPORT_EMPTY',
    ];

    private $APP = 'emprendamos_juntos';

    public function __construct()
    {
        $this->CHANNEL = 'export_errors';
    }

    public function exportGroupFailure(ExportRequest $request)
    {
        try {
            $current_date = now()->format('Y-m-d');
            $group = Group::findOrFail($request->fk_group);
            $promoter = $group->promoter;

            $groupname =  $group->groupname . ' ' . explode(' ', $promoter->firstname)[0];

            $data = $this->getGroupFailureData($request);

            if (empty($data)) {
                return $this->responseJson($this->MESSAGES['EMPTY'], null, 501);
            }

            $path = storage_path("app/templates/{$this->APP}/cardsale_template.xlsx");

            if (!file_exists($path)) {
                throw new Exception("Template file not found at path: {$path}");
            }

            return Excel::download(
                new GroupFailureExport($data),
                "{$current_date}_{$groupname}.xlsx",
                ExcelFormat::XLSX,
                [
                    'template' => $path
                ]
            );
        } catch (Exception $ex) {
            $this->generateLog($this->CHANNEL, $ex);
            return $this->responseJson($this->MESSAGES['GROUPFAILURE'], null, 501);
        }
    }
}
