<?php

namespace Modules\StockIssues\Http\Controllers;

use App\BusinessLocation;
use App\User;
use Exception;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
use Modules\StockIssues\Models\StockReport;
use Spatie\Dropbox\Client as DropboxClient;

class StockReportController extends \App\Http\Controllers\OpeningStockController
{
    /**
     * @param Request $request
     * @return Application|Factory|View
     */
    public function index(Request $request)
    {
        if (!auth()->user()->can('stock-issues.reports'))
            abort(403, 'Unauthorized action.');
        Paginator::useBootstrapThree();
        $permitted_locations = Auth::user()->permitted_locations();
        if ($permitted_locations === 'all') {
            $business_id = request()->session()->get('user.business_id');
            $business_locations = BusinessLocation::query()->where('business_id', $business_id)->get();
        } else
            $business_locations = BusinessLocation::query()->whereIn('id', $permitted_locations)->get();
        $reports = null;
        if ($request->has('filter_location_id')) {
            $reports = StockReport::query()->with([
                'business_location'
            ]);
            if (!auth()->user()->can('stock-issues.pm-delete-reports'))
                $reports->whereNull('deleted_at');
            if (!empty($request->get('filter_location_id')))
                $reports = $reports->where('business_location_id', $request->get('filter_location_id'));
            else
                $reports = $reports->whereIn('business_location_id', $business_locations->pluck('id'));
            $reports = $reports->paginate(15);
        }
        $business_locations = $business_locations->mapWithKeys(function ($location) {
            return [$location->id => "$location->name ($location->location_id)"];
        });
        return view('stock-issues::reports', array_merge(compact('business_locations', 'reports'), [
            'cronJob' => $this->getCronJobCommand(),
            'cronJobFix' => $this->getCronJobCommandWithFix(),
        ]));
    }

    /**
     * @param Request $request
     * @param StockReport $stockReport
     * @return RedirectResponse
     */
    public function download(Request $request, StockReport $stockReport)
    {
        if (!auth()->user()->can('stock-issues.reports') || !auth()->user()->can('location.' . $stockReport->business_location_id))
            abort(403, 'Unauthorized action.');
        try {
            if (!is_null($stockReport->deleted_at))
                throw new Exception();
            $client = new DropboxClient(env('DROPBOX_ACCESS_TOKEN'));
            return redirect()->to($client->getTemporaryLink($stockReport->path));
        } catch (Exception $exception) {
            return redirect()->back()->with('status', [
                'success' => 0,
                'msg' => 'File NotFound Contact Admin !'
            ]);
        }
    }

    /**
     * @param Request $request
     * @param StockReport $stockReport
     * @return RedirectResponse
     * @throws Exception
     */
    public function delete(Request $request, StockReport $stockReport)
    {
        if (
            !auth()->user()->can('stock-issues.reports') ||
            !auth()->user()->can('stock-issues.delete-reports') ||
            !auth()->user()->can('location.' . $stockReport->business_location_id)
        )
            abort(403, 'Unauthorized action.');
        try {
            if (!is_null($stockReport->deleted_at))
                throw new Exception();
            $stockReport->update([
                'deleted_at' => now()
            ]);
            return redirect()->back()->with('status', [
                'success' => 1,
                'msg' => 'File Deleted Successfully .'
            ]);
        } catch (Exception $exception) {
            return redirect()->back()->with('status', [
                'success' => 0,
                'msg' => 'File NotFound Contact Admin !'
            ]);
        }
    }

    /**
     * @param Request $request
     * @param StockReport $stockReport
     * @return RedirectResponse
     * @throws Exception
     */
    public function permanentlyDelete(Request $request, StockReport $stockReport)
    {
        if (
            !auth()->user()->can('stock-issues.reports') ||
            !auth()->user()->can('stock-issues.pm-delete-reports') ||
            !auth()->user()->can('location.' . $stockReport->business_location_id)
        )
            abort(403, 'Unauthorized action.');
        try {
            $stockReport->delete();
            return redirect()->back()->with('status', [
                'success' => 1,
                'msg' => 'File Deleted Successfully .'
            ]);
        } catch (Exception $exception) {
            return redirect()->back()->with('status', [
                'success' => 0,
                'msg' => 'unexpected error !'
            ]);
        }
    }

    public function getCronJobCommand()
    {
        $php_binary_path = empty(PHP_BINARY) ? "php" : PHP_BINARY;

        $command = "* * * * * " . $php_binary_path . " " . base_path('artisan') . " stock:report >> /dev/null 2>&1";

        if (config('app.env') == 'demo') {
            $command = '';
        }

        return $command;
    }

    public function getCronJobCommandWithFix()
    {
        $php_binary_path = empty(PHP_BINARY) ? "php" : PHP_BINARY;

        $command = "* * * * * " . $php_binary_path . " " . base_path('artisan') . " stock:report --fix >> /dev/null 2>&1";

        if (config('app.env') == 'demo') {
            $command = '';
        }

        return $command;
    }
}
