<?php

namespace App\Http\Controllers\Resources;

use Illuminate\Http\Request;
use App\Http\Requests\PurchaseOrderRequest;
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\Mail;
use App\Mail\PurchaseOrderEmail;

use App\PurchaseOrder;
use App\Quotation;

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

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

    /**
     * Store a newly created resource in storage.
     *
     * @param  App\Http\Requests\PurchaseOrderRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(PurchaseOrderRequest $request)
    {
      return response()->json(tap(new PurchaseOrder($request->all()), function ($order) use ($request) {
          $order->saveModel($request, 'OC-');
          $order->details()->createMany($request['details']);
          $order->load('quotation','supplier');          $order->details()->createMany($request['details']);
      }), 201);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
      $order=PurchaseOrder::with('details')->find($id);

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

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

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

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

      return tap($order)->updateDetails($request);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
      $order=PurchaseOrder::find($id);

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

      $order->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(PurchaseOrderRequest $request)
    {
      foreach ($request->input('ids') as $id) {
        $order=PurchaseOrder::find($id);

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

      foreach ($request->input('ids') as $id) {
        $order=PurchaseOrder::find($id);

        $order->delete();
      }

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

    /**
     * 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 PurchaseOrder, $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
          __('purchase_orders.folio') => 'folio',
          __('purchase_orders.total') => 'total',
          __('purchase_orders.status') => function($status) { // You can do if statement or any action do you want inside this closure
              return ($status->status == 1) ? __('purchase_orders.pending') : __('purchase_orders.approved');
          },
      ];

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

    public function approved($id)
    {
      $order=PurchaseOrder::with('details')->find($id);

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

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

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

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

      $order->status = PurchaseOrder::APPROVED;
      $order->save();

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

    public function cancelled($id)
    {
      $order=PurchaseOrder::find($id);

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

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

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

      $order->status = PurchaseOrder::CANCELLED;
      $order->save();

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

    public function paid($id)
    {
      $order=PurchaseOrder::find($id);

      if ($order->status == PurchaseOrder::PENDING) {
        return response()->json(['errors'=>array(['code'=>400,'message'=>__('purchase_orders.pending')])],400);
      }

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

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

      $order->status = PurchaseOrder::PAID;
      $order->save();

      if ($order->quotation->total_paid) {
        $order->quotation->update(['status' => Quotation::PAID]);
      }

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

    /**
     * Send email of the resource.
     *
     * @param  App\Http\Requests\Request $request
     * @return \Illuminate\Http\Response
     */
    public function email (Request $request, $id) {

       $user =  \JWTAuth::parseToken()->authenticate();
       $subject = $request->input('subject');
       $body = $request->input('body');
       $order = PurchaseOrder::find($id);

       Mail::to($request->input('email'))->send(new PurchaseOrderEmail($user, $subject, $body, $order));

       if( count(Mail::failures()) > 0 ) {
          foreach(Mail::failures() as $email_address) {
              return response()->json(['errors'=>array(['code'=>422,'message'=>__('purchase_orders.cancelled')])],422);
           }
       } else {
           return response()->json($order, 200);
       }
    }
}
