<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\CustomerAdjustment;
use Illuminate\Support\Facades\Validator;

class CustomerAdjustmentController extends Controller
{


    public function alladjustments() {

        $adjustments = CustomerAdjustment::with('receipt')->orderBy('created_at','desc')->get();

        return view('transaction/adjustment.index',compact('adjustments'));
    }

    public function getAdjustmentDetial($id) {

        $adjustment = CustomerAdjustment::where('id',$id)->with('receipt')->first();

        return view('transaction/adjustment.detail-adjustment',compact('adjustment'));
    }

    public function editAdjustmentForm($id) {

        $adjustment = CustomerAdjustment::where('id',$id)->with('receipt')->first();

        return view('transaction/adjustment.edit-adjustment',compact('adjustment'));
    }

    public function updateAdjustment(Request $request) {

        $messages = [
            'sold_amount.required_if' => 'The Sold Amount is required,when status change to sold.',
            ];

        $validator = Validator::make($request->all(), [
                   'status' => 'required',
                   'sold_amount' => 'required_if:status,0'
        ],$messages);

        if ($validator->fails()) {
            return redirect('/adjustment/edit/' . $request->id)
                            ->withErrors($validator)
                            ->withInput()
                            ->with([
                                'message' => 'Invalid Inputs!',
                                'alert-type' => 'error',
            ]);
        }

        //update customer
        CustomerAdjustment::where('id',$request->id)->update(['description'=>$request->description,'status'=>$request->status,'sold_amount'=>$request->sold_amount]);

        return redirect()
                        ->route('adjustment.detail', ['id' => $request->id])
                        ->with([
                            'message' => 'Adjustment updated successfully!',
                            'alert-type' => 'info'
        ]);
    }
}
