<?php

namespace App\Http\Controllers;

use App\Models\Company;
use App\Models\FgDetails;
use App\Models\FinishedGood;
use App\Models\Order;
use App\Models\OrderDetails;
use App\Models\OrderStatus;
use App\Models\QC;
use App\Models\QcDetails;
use App\Models\Status;
use App\Services\InventorySetup\FinishedGoodService;
use App\Transformers\GrnTransformer;
use Illuminate\Http\req;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class FinishedGoodController extends Controller
{

    private $systemService;

    private $grnTransformer;

    public function __construct(FinishedGoodService $finishedGood, GrnTransformer $grnTransformer)
    {
        $this->systemService = $finishedGood;
        $this->grnTransformer = $grnTransformer;
    }

    public function index(Request $request)
    {
        $title = 'Finished Good List';
        return view('backend.pages.finishedgood.index_qc', get_defined_vars());
    }

    public function create(){
        $title = 'Finished Good';
        $orders = Order::with('details')->get();
        return view('backend.pages.finishedgood.create_qc', get_defined_vars());
    }
    
    public function dataqc(Request $request)
    {
        $json_data = $this->systemService->getList($request);
        return json_encode($this->grnTransformer->dataTable($json_data));
    }

   public function searchgrn(Request $request)
    {
        $data = '';
        $purchasedetails = QC::where('order_voucher_id', $request->id)->orderBy("id",'desc')->first();
        $purchase = Order::find($request->id);

        $grnDetails = FgDetails::where('order_voucher', $request->id)->latest()->orderBy('id', 'asc')->take(count($purchasedetails->details))->get();

        if (!$grnDetails->isEmpty()) {
            $convertarray = $grnDetails->toArray();
        } else {
            $convertarray = null;
        }

        $qty = 0;
        $approve_qty = 0;
        $remaining_qty = 0;

        // dd($convertarray);
        if (empty($convertarray)) {
            // dd('1st');
            foreach ($purchasedetails->details as $key => $value) {
                $product = OrderDetails::find($value->product_id);
                $qty += $value->approve_qty;
                $approve_qty += 0;
                $remaining_qty += $value->approve_qty;
                $data .= '<tr class="delrow">
    <td class="text-right">' . $product->goods_name . '<input type="hidden" class="add_quantity" name="product_id[]" value="' . $product->id . '"></td>
    <td class="text-right">' . $product->size . '<input type="hidden" class="size" name="size[]" value="' . $product->size  . '"></td>
    <td class="text-right">' . $product->color . '<input type="hidden" class="color" name="color[]" value="' . $product->color  . '"></td>
    <td class="text-right">' . $product->unit . '<input type="hidden" class="unit" name="unit[]" value="' . $product->unit  . '"></td>
    <td class="text-right">' . $value->approve_qty . '<input type="hidden" class="add_quantity" name="qty[]" value="' . $value->approve_qty  . '"></td>
    <td class="text-right">' .  ' <input class="ttlqty form-control" type="text" readonly name="approve_qty[]" value="' . 0 . '"></td>
    <td class="text-right">' .  ' <input class="remaining qty form-control" min="0" type="number" value="' . $value->approve_qty . '" name="remaining[]"></td>
      </tr>';
            }
        } else {
            foreach ($purchasedetails->details as $key => $value) {
                $product = OrderDetails::find($value->product_id);
                $calculate = $convertarray[$key]['qty'] - $convertarray[$key]['approve_qty'];
                $qty += $convertarray[$key]['qty'];
                $approve_qty +=$convertarray[$key]['approve_qty'];
                $remaining_qty += $calculate;
                
                $data .= '<tr class="delrow">
    <td class="text-right">' . $product->goods_name . '<input type="hidden" class="add_quantity" name="product_id[]" value="' . $product->id  . '"></td>
    <td class="text-right">' . $product->size . '<input type="hidden" class="size" name="size[]" value="' . $product->size  . '"></td>
    <td class="text-right">' . $product->color . '<input type="hidden" class="color" name="color[]" value="' . $product->color  . '"></td>
    <td class="text-right">' . $product->unit . '<input type="hidden" class="unit" name="unit[]" value="' . $product->unit  . '"></td>
    <td class="text-right">' .  ' <input class="ttlqty form-control" type="text" readonly name="qty[]" value="' . $convertarray[$key]['qty'] . '"></td>
    <td class="text-right">' .  ' <input class="approve form-control  approve_qty" readonly value="' . $convertarray[$key]['approve_qty'] . '" type="text" name="approve_qty[]"></td>
    <td class="text-right">' .  ' <input class="remaining qty form-control" min="0" type="number" value="' . $calculate . '" name="remaining[]"></td>

      </tr>';
            }
        }

        $footer = '
        <tr>
            <td colspan="4">Total</td>
            <td class="text-right"><strong class="approvett">'.$qty.'</strong></td>
            <td class="text-right"><strong class="remainingtt">'.$approve_qty.'</strong></td>
            <td class="text-right"><strong class="ttlunitprice">'.$remaining_qty.'</strong></td>
        </tr>
     ';

        return ['prdetails' => $data, "footer"=>$footer];
    }

    public function store(Request $request)
    {
        try {
            $this->validate($request, $this->systemService->storeValidation($request));
        } catch (ValidationException $e) {
            session()->flash('error', 'Validation error !!');
            return redirect()->back()->withErrors($e->errors())->withInput();
        }
        $this->systemService->store($request);
        session()->flash('success', 'Data successfully save!!');
        return redirect()->route('finished.goods.index');
    }

    public function invoice($id)
    {
        if (!is_numeric($id)) {
            session()->flash('error', 'Invoice id must be numeric!!');
            return redirect()->back();
        }

        $editInfo = $this->systemService->details($id);
        if (!$editInfo) {
            session()->flash('error', 'Invoice info is invalid!!');
            return redirect()->back();
        }
        $title = 'Good Received Note ';
        $orders = Status::orderBy("order_by","asc")->get(); 
        $fg = FinishedGood::findOrFail($id);
        $fgDetails = FgDetails::where('fg_id', $id)->get();
        $companyInfo = Company::latest('id')->first();
        $orderstatus = OrderStatus::where('fg_id',$id)->get();

        return view('backend.pages.finishedgood.approve', get_defined_vars());
    }

    public function statusupdate(Request $req,$id)
    {
        $orderstatus = new OrderStatus();
        if ($req->file('file')) {
                $orderAttachment = 'attachment_' . time() . '_' . $req->file('file')->getClientOriginalExtension();
                $req->file('file')->move(public_path('/uploads/status/orders/'), $orderAttachment);
        }else{
            $orderAttachment = null;
        }

        $fg = FinishedGood::find($id);
        $fg->status = $req->status;
        $fg->save();

        $orderstatus->fg_id = $id;
        $orderstatus->name = $req->status;
        $orderstatus->file = $orderAttachment;
        $orderstatus->save();

        session()->flash('success', 'Status successfully Updated!!');
        return  redirect()->back();
    }
}
