<?php

namespace App\Http\Controllers;

use App\Models\InstallRequest;
use App\Models\InstallRequestPhoto;
use Illuminate\Http\Request;
use App\Exports\RequestsExport;
use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\Exception;
use ZipArchive;

class RequestController extends Controller
{
    /**
     * @throws Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function export(Request $request)
    {
        $filters = [
            'start_date' => $request->input('date_from'),
            'end_date'   => $request->input('date_to'),
            'status'     => $request->input('status'),
            'installer_id' => $request->input('installer_id'),
            'address'    => $request->input('address'),
        ];

        return Excel::download(
            new RequestsExport($filters),
            'applications_' . now()->format('Y-m-d_H-i') . '.xlsx'
        );
    }

    public function downloadMedia($id)
    {
        $request = InstallRequest::with('photos')->findOrFail($id);

        if (!$request->photos->count()) {
            return back()->with('error', 'Нет файлов для скачивания');
        }

        $zip = new ZipArchive();
        $fileName = "request_{$id}_media.zip";
        $zipPath = storage_path("app/public/{$fileName}");

        if ($zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE) === true) {

            foreach ($request->photos as $media) {
                $filePath = storage_path('app/public/' . $media->path);

                if (file_exists($filePath)) {
                    $zip->addFile($filePath, basename($filePath));
                }
            }

            $zip->close();
        }

        return response()->download($zipPath)->deleteFileAfterSend(true);
    }
}
