<?php

namespace App\Http\Controllers\Resources;

use Illuminate\Http\Request;
use App\Http\Requests\{{model}}Request;
use App\Http\Requests\ExportRequest;
use App\Http\Requests\ImportRequest;
use App\Http\ReportGenerator\PdfReport;
use App\Http\ReportGenerator\ExcelReport;
use App\Http\Controllers\Controller;
use App\Http\Filters\QueryBuilder;
use Illuminate\Support\Facades\Notification;
// use App\Notifications\{{model}}Created;

use App\{{model}};
use Auth;

class {{model}}Controller extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $queryBuilder = new QueryBuilder(new {{model}}, $request);

        return response()->json($queryBuilder->build()->paginate(10), 200);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  App\Http\Requests\{{model}}Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store({{model}}Request $request)
    {
        return response()->json(tap(new {{model}}($request->all()), function (${{varModel}}) use ($request) {
            ${{varModel}}->save();

            // $users = {{model}}::role('Admin')->get();
            // Notification::send($users, new {{model}}Created($data));
            // auth()->{{varModel}}()->notify(new {{model}}Created(${{varModel}}->id));
        }), 201);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        ${{varModel}} = {{model}}::find($id);

        if (!${{varModel}}) {
            return response()->json(['errors' => array(['code' => 404, 'message' => __('{{varPluralModel}}.not_find')])], 404);
        }

        return response()->json(['status' => 'ok', 'data' => ${{varModel}}], 200);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  App\Http\Requests\{{model}}Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update({{model}}Request $request, $id)
    {
        ${{varModel}} = {{model}}::find($id);

        if (!${{varModel}}) {
            return response()->json(['errors' => array(['code' => 404, 'message' => __('{{varPluralModel}}.not_find')])], 404);
        }

        return tap(${{varModel}})->update($request->all());
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy({{model}}Request $request, $id)
    {
        ${{varModel}} = {{model}}::find($id);

        if (!${{varModel}}) {
            return response()->json(['errors' => array(['code' => 404, 'message' => __('{{varPluralModel}}.not_find')])], 404);
        }

        ${{varModel}}->delete();

        return response()->json(['code' => 204, 'message' => __('strings.deleted_successfully')], 204);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  array  $id
     * @return \Illuminate\Http\Response
     */
    public function destroyMany({{model}}Request $request)
    {
        foreach ($request->input('ids') as $id) {
            ${{varModel}} = {{model}}::find($id);

            if (!${{varModel}}) {
                return response()->json(['errors' => array(['code' => 404, 'message' => __('{{varPluralModel}}.not_find')])], 404);
            }
        }

        foreach ($request->input('ids') as $id) {
            ${{varModel}} = {{model}}::find($id);

            ${{varModel}}->delete();
        }

        return response()->json(['code' => 204, 'message' => __('strings.deleted_successfully')], 204);
    }

    public function action($id)
    {
      ${{varModel}}={{model}}::with('details')->find($id);

      if (!${{varModel}}) {
        return response()->json(['errors'=>array(['code'=>404,'message'=>__('{{varPluralModel}}.not_find')])],404);
      }

      if (${{varModel}}->status == {{model}}::APPROVED) {
        return response()->json(['errors'=>array(['code'=>400,'message'=>__('{{varPluralModel}}.approved')])],400);
      }

      if (${{varModel}}->status == {{model}}::CANCELLED) {
        return response()->json(['errors'=>array(['code'=>400,'message'=>__('{{varPluralModel}}.cancelled')])],400);
      }

      if (${{varModel}}->status == {{model}}::PAID) {
        return response()->json(['errors'=>array(['code'=>400,'message'=>__('{{varPluralModel}}.paid')])],400);
      }

      ${{varModel}}->status = {{model}}::APPROVED;
      ${{varModel}}->save();

      return response()->json(${{varModel}}, 200);
    }

    /**
     * Display report from a listing of the resource.
     *
     * @param  App\Http\Requests\ExportRequest $request
     * @return PDF CSV or XLS
     */
    public function export(ExportRequest $request)
    {
        $format = $request->input('format');
        $orderBy = $request->input('order_by');
        $betweenDates = ($request->input('between_dates')) ? explode(',', $request->input('between_dates')) : ['', ''];

        $queryBuilder = new QueryBuilder(new {{model}}, $request);

        $meta = [ // For displaying filters description on header
            __('strings.registered_on') => $betweenDates[0] . ' - ' . $betweenDates[1],
            __('strings.order_by') => $orderBy,
        ];

        $columns = [ // Set Column to be displayed
/*             __('{{varPluralModel}}.name') => 'name',
            __('{{varPluralModel}}.email') => 'email',
            __('{{varPluralModel}}.role') => function (${{varModel}}) {
                return ${{varModel}}->view_permissions[0];
            },
            __('{{varPluralModel}}.status') => 'status', */
        ];

        switch ($format) {
            case 'pdf':
                $report = new PdfReport();
                return $report->of(__('{{varPluralModel}}.report_title'), $meta, $queryBuilder->build()->get(), $columns)->download(__('{{varPluralModel}}.report_title'));
            case 'excel':
                $report = new ExcelReport();
                return $report->of(__('{{varPluralModel}}.report_title'), $meta, $queryBuilder->build()->get(), $columns)->setView('reports.list-excel-template')->download(__('{{varPluralModel}}.report_title'));
            case 'csv':
                $report = new ExcelReport();
                return $report->of(__('{{varPluralModel}}.report_title'), $meta, $queryBuilder->build()->get(), $columns)->simple()->setFormat('csv')->download(__('{{varPluralModel}}.report_title'));
            default:
                $report = new PdfReport();
                return $report->of(__('{{varPluralModel}}.report_title'), $meta, $queryBuilder->build()->get(), $columns)->stream();
        }
    }


    /**
     * Import a listing of the resource.
     *
     * @param  App\Http\Requests\ImportRequest $request
     * @return \Illuminate\Http\Response
     */
    public function import(ImportRequest $request)
    {
      $path = $request->file('importFile')->getRealPath();

      Excel::filter('chunk')->load($path)->chunk(250, function($results) {
          foreach($results as ${{varModel}})
          {
            {{model}}::create([
              // 'sku' => ${{varModel}}->sku,
            ]);
          }
      });

      return response()->json(['code'=>200,'message'=>__('strings.imported_successfully')],200);
    }

    /**
     * Dowload template.
     *
     * @return File CSV
     */
    public function template()
    {
      $columns = [ // Set Column to be displayed
/*         'sku',
        'name',
        'number_part',
        'price',
        'unit_measurement_id',
        'currency_id' */
      ];

      $report = new ExcelReport();
      return $report->of(__('{{varPluralModel}}.template'), [], collect(), $columns)->showNumColumn(false)->showMeta(false)->setFormat('csv')->simpleDownload(__('{{varPluralModel}}.template'));
    }
}
