/**
  * Process form request to create report
  *
  * This will generate report for distribution
  * realization.
  *
  * @param Request $request
  * @return Response
  */
 public function postDistRealization(Request $request)
 {
     $this->validate($request, ['edition_id' => 'required|numeric']);
     /**
             // Prepare data for report
             $DistPlan = DistPlan::with('details.agent')
        ->where('edition_id', '=', $request->edition_id)
        ->first();
     
             $DistReal = DistRealization::with('details.agent')
        ->where('edition_id', '=', $request->edition_id)
        ->first();
     */
     $DistPlan = DistPlan::where('edition_id', '=', $request->edition_id)->first();
     $DistReal = DistRealization::with('edition.magazine')->where('edition_id', '=', $request->edition_id)->first();
     // if empty, don't render any result
     if (!$DistPlan or !$DistReal) {
         $msg = "Tidak ditemukan perencanaan atau realisasi";
         return redirect('report/create-dist-realization')->with('errMsg', $msg);
     }
     $DistPlanDet = DistPlanDet::with('agent.agent_category')->where('distribution_plan_id', '=', $DistPlan->id)->get();
     $DistRealDet = DistRealDet::with('agent.agent_category')->where('distribution_realization_id', '=', $DistReal->id)->get();
     // Change structure so that $DistPlanDet
     // and $DistRealDet are keyed by agent_id
     $agent_DistPlanDet = $DistPlanDet->keyBy('agent_id');
     $agent_DistRealDet = $DistRealDet->keyBy('agent_id');
     // Get agent details
     $keys = $agent_DistPlanDet->keys();
     $agents = Agent::with('agent_category')->whereIn('id', $keys->all())->orderBy('agent_category_id', 'asc')->get();
     // Now, return agents aggregat
     return view('report/preview-dist-realization', ['distReal' => $DistReal, 'distPlanDet' => $agent_DistPlanDet, 'distRealDet' => $agent_DistRealDet, 'agents' => $agents]);
 }
 /**
  * Store a newly created resource in storage.
  *
  * @return Response
  */
 public function store(Request $request)
 {
     $this->validate($request, ['dist_plan_id' => 'required|numeric']);
     $distPlanID = $request->input('dist_plan_id');
     // Get distPlan
     try {
         // validate if dist_plan is already realized
         $distPlan = DistPlan::with('details')->where('is_realized', '=', 0)->findOrFail($distPlanID);
     } catch (ModelNotFoundException $e) {
         $execMsg = "Distribution plan is not found or has been realized.";
         return redirect('circulation/distribution-realization')->with('errMsg', $execMsg);
     }
     // The big work starts here
     // dist_plan exist, and not yet realized,
     // generate exact data for dist_realize from dist_plan (manually assign)
     $distReal = new DistRealize();
     $distReal->distribution_plan_id = $distPlanID;
     $distReal->edition_id = $distPlan->edition_id;
     $distReal->print = $distPlan->print;
     $distReal->gratis = $distPlan->gratis;
     $distReal->distributed = $distPlan->distributed;
     $distReal->stock = $distPlan->stock;
     $distReal->date = $distPlan->publish_date;
     $distReal->print_number = $distPlan->print_number;
     $distReal->save();
     // make dist_plan.is_realized set to 1
     $distPlan->is_realized = 1;
     $distPlan->save();
     // generate exact data for dist_realize_details from dist_plan_details
     foreach ($distPlan->details as $distPlanDet) {
         $distRealDet = new DistRealizeDetail();
         $distRealDet->dist_real_id = $distReal->id;
         $distRealDet->agent_id = $distPlanDet->agent_id;
         $distRealDet->save();
     }
     // done
     return redirect('circulation/distribution-realization');
 }
 /**
  * Display the specified resource.
  *
  * @param  int  $id
  * @return Response
  */
 public function show($distRealizationID, $distRealizationDetID, $id)
 {
     $delivery = DistRealizationDet::with('distributionRealization.edition.magazine', 'agent', 'delivery')->find($distRealizationDetID);
     return view('circulation/delivery-details', ['dlv' => $delivery, 'deliveryID' => $id]);
 }
 /**
  * return true if item are returnable
  *
  * Return criterias are:
  *  - return number is not existed before
  *  - sum is less than or equal to total delivered item
  *
  *  @param Array input from form validation
  *  @param int edition_id
  *  @param int total returned amount on form
  *
  *  @return int distRealDetID if passed all exceptions
  */
 private function validateReturnItem($input, $edition_id, $total)
 {
     // Check if return.num already existed
     $existed = ReturnItem::where('num', '=', (int) $input['number'])->get();
     if (!$existed->isEmpty()) {
         $err = "Return number is already existed! Return#: {$existed->implode('number')}";
         throw new \Exception($err);
     }
     // Check if agent_id match to distribution_plan
     $realizationDetail = DistRealDet::with('distributionRealization')->where('agent_id', '=', $input['agent_id'])->get();
     if ($realizationDetail->isEmpty()) {
         $err = 'No delivery was made for this agent';
         throw new \Exception($err);
     }
     $distRealDetID = 0;
     // look for each distributionPlan
     foreach ($realizationDetail as $rd) {
         if ($rd->distributionRealization->edition_id == (int) $edition_id) {
             $distRealDetID = (int) $rd->id;
         }
     }
     if ($distRealDetID == 0) {
         $err = 'No editions were delivered for this agent';
         throw new \Exception($err);
     }
     //Previous returns
     $returnAmount = 0;
     $prevRets = ReturnItem::where('dist_realization_det_id', '=', $distRealDetID)->get();
     if ($prevRets) {
         foreach ($prevRets as $x) {
             $returnAmount += $x->total;
         }
     }
     $total = $returnAmount + $total;
     // Delivery amount is less than return
     $deliveryAmount = 0;
     $deliveries = Delivery::where('dist_realization_det_id', '=', $distRealDetID)->get();
     if ($deliveries) {
         foreach ($deliveries as $x) {
             // Quota cannot be returned, so use consigned amount
             $deliveryAmount += $x->consigned;
         }
     }
     if ($deliveryAmount < $total) {
         //Must fail
         $err = "Mismatched return amount!" . " Deliveries made = {$deliveryAmount}." . " Total returned amount = {$total}.";
         throw new \Exception($err);
     }
     return $distRealDetID;
 }