<?php

namespace Ignite\Core\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Ignite\Core\Entities\Report;
use Ignite\Core\Models\Grid\ReportTable;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Mail;

class ReportController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @param  ReportTable $table
     * @param  Request     $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function index(ReportTable $table, Request $request)
    {
        if ($request->wantsJson()) {
            return $table->ajax();
        }

        return $table->render('Core::admin.report.index');
    }

    /**
     * Show the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\JsonResponse|\Illuminate\View\View
     */
    public function show($id, Request $request)
    {
        /** @var Report $report */
        $report = Report::find((int) $id);

        if (! $report->isPublished()) {
            flash()->error(sprintf(
                "The requested report `%s` is not available until %s",
                $report->getName(),
                $report->published_at->format('F j Y')
            ))->important();
            return redirect()->route('admin.reports.index');
        }

        if ($report->isSensitive()) {
            flash()->error('The requested report contains sensitive information which cannot be viewed via the web interface.')->important();
            return redirect()->route('admin.reports.index');
        }

        /** @var \Ignite\Core\Models\Grid\AbstractTable $table */
        $table = $report->getReportClassInstance();

        if ($request->wantsJson()) {
            return $table->ajax();
        }

        return $table->render('Core::admin.report.show', compact('report'));
    }

    public function send($id)
    {
        /** @var Report $report */
        $report = Report::find((int) $id);

        if (! $report->isSensitive()) {
            flash()->error("The requested report `{$report->getName()}` does not contain sensitive information, you are free to view via the web interface.")->important();
            return redirect()->route('admin.reports.show', $report);
        }

        /** @var \Ignite\Core\Models\Grid\AbstractTable $table */
        $table = $report->getReportClassInstance();

        $table->storeAsExcel($filepath = $report->getFilename('reports'));

        //return new TaxReport($filepath);
        // TODO: Implement the logic to send the sensitive file to Box.com via their API.
    }
}
