<?php

namespace App\Http\Controllers;

use App\Models\Company;
use App\Models\Order;
use App\Models\PurchaseOrder;
use App\Models\Purchases;
use App\Models\Grn_detail;
use App\Models\OrderDetails;
use App\Models\PurchasesDetails;
use App\Models\QC;
use App\Models\QcDetails;
use App\Services\InventorySetup\QCService;
use App\Transformers\GrnTransformer;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;

class QCController extends Controller

{
    private $systemService;

    private $grnTransformer;


    public function __construct(QCService $qcservice, GrnTransformer $grnTransformer)
    {
        $this->systemService = $qcservice;

        $this->grnTransformer = $grnTransformer;
    }

    public function index(Request $request)
    {
        $title = 'Purchase Requisition List';
        return view('backend.pages.qc.index_qc', get_defined_vars());
    }

    public function create(){
        $title = 'QC';
        $orders = Order::with('details')->where('status', "!=" ,"Confirmed")->get();
        return view('backend.pages.qc.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 = OrderDetails::where('order_id', $request->id)->get();
        $purchase = Order::find($request->id);

        $grnDetails = QcDetails::where('order_voucher', $request->id)->latest()->orderBy('id', 'asc')->take(count($purchasedetails))->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 as $key => $value) {
                $qty += $value->quantity;
                $approve_qty += 0;
                $remaining_qty += $value->quantity;
                $data .= '<tr class="delrow">
    <td class="text-right">' . $value->goods_name . '<input type="hidden" class="add_quantity" name="product_id[]" value="' . $value->id . '"></td>
    <td class="text-right">' . $value->size . '<input type="hidden" class="size" name="size[]" value="' . $value->size  . '"></td>
    <td class="text-right">' . $value->color . '<input type="hidden" class="color" name="color[]" value="' . $value->color  . '"></td>
    <td class="text-right">' . $value->unit . '<input type="hidden" class="unit" name="unit[]" value="' . $value->unit  . '"></td>
    <td class="text-right">' . $value->quantity . '<input type="hidden" class="add_quantity" name="qty[]" value="' . $value->quantity  . '"></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->quantity . '" name="remaining[]"></td>
      </tr>';
            }
        } else {
            foreach ($purchasedetails as $key => $value) {

                $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">' . $value->goods_name . '<input type="hidden" class="add_quantity" name="product_id[]" value="' . $value->id  . '"></td>
    <td class="text-right">' . $value->size . '<input type="hidden" class="size" name="size[]" value="' . $value->size  . '"></td>
    <td class="text-right">' . $value->color . '<input type="hidden" class="color" name="color[]" value="' . $value->color  . '"></td>
    <td class="text-right">' . $value->unit . '<input type="hidden" class="unit" name="unit[]" value="' . $value->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('delivery.qc.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 ';
        $grn = QC::findOrFail($id);
        $grnDetails = QcDetails::where('qc_id', $id)->get();
        $companyInfo = Company::latest('id')->first();
        return view('backend.pages.qc.approve', get_defined_vars());
    }
}
