<?php

namespace App\Services\Settings;

use App\Models\Asset;

/**
 * Service Class for Manufacturer Export
 */
class Manufacturer
{

    /**
     * Retrieve manufacturer data, starting from a given index, and appending nested data for each manufacturer.
     *
     * @param array $manufacturers The list of manufacturers to process.
     * @param int   $start         The starting index.
     * @param array $data          The initial data array to which the nested data will be appended.
     *
     * @return array The updated data array with nested manufacturer data.
     */
    public function getManufacturerData($manufacturers, $start, $data)
    {
        $parentIndex = $start;

        foreach ($manufacturers as $manufacturer) {
            $parentIndex++;
            $nestedData = $this->getNestedData($manufacturer);
            $data[] = $nestedData;
        }

        return $data;
    }

    /**
     * Retrieve nested data for a given manufacturer.
     *
     * @param object $manufacturer The manufacturer object containing the manufacturer details.
     *
     * @return array An associative array containing the manufacturer's name and the number of assets.
     */
    public function getNestedData($manufacturer)
    {
        $nestedData = [];

        $nestedData['name']         = $manufacturer->name;
        $nestedData['no_of_assets'] = Asset::whereHas('MakeAndModel', function ($query) use ($manufacturer) {
            $query->where('manufacturer_id', $manufacturer->id);
        })->count();

        return $nestedData;
    }

    /**
     * Export the provided data as a CSV file and initiate a download.
     *
     * @param array $datas The data to be exported, structured as an array of arrays.
     *
     * @return \Illuminate\Http\Response The HTTP response containing the CSV file for download.
     */
    public function export($datas)
    {
        $headers = array(
            "Content-type" => "text/csv",
            "Content-Disposition" => "attachment; filename=file.csv",
            "Pragma" => "no-cache",
            "Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
            "Expires" => "0"
        );

        $callback = function () use ($datas) {
            $file = fopen('php://output', 'w');
            fputcsv($file, array_keys($datas[0][0]));

            foreach ($datas as $data) {
                foreach ($data as $data) {
                    fputcsv($file, $data);
                }
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
}
