<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\ComparativeStatement;
use App\ItemPurchaseRequest;
use App\PurchaseRequest;
use Illuminate\Support\Facades\Crypt;
use DB;
use App\PurchaseRequestVendor;
use App\ItemVendor;
use App\PurchaseOrder;
use App\ItemPurchaseOrder;
use App\RequestForQuotation;
use App\Role;
use App\ComparativeStatementDocument;

class ComparativeStatementController extends Controller
{

    public function __construct()
    {
    }
    public function index()
    {
        $purchase_requests = PurchaseRequest::orderBy('id', 'DESC')->where([['status', '>', 4]])->get();
        return view('procurement/comparative-statement.index', compact('purchase_requests'));
    }
    public function send(Request $request)
    {



        $pr_id = $request->pr_id;
        $vendor_id = $request->vendor_id;
        $item_ids = explode(',', $request->item_ids);
        $vendor_prices = explode(',', $request->vendor_prices);
        $vendor_messages = explode(',', $request->vendor_messages);


        $file_length = $request->file_length;

        $supported_image = array(
            'gif',
            'jpg',
            'JPG',
            'jpeg',
            'png',
            'PNG',
            'docx',
            'pdf',
        );

        $images = array();

        $is_valid =  PurchaseRequest::where('id', '=', $pr_id)->first();

        if ($is_valid == true) {

            if (strtotime(date('Y-m-d')) > strtotime(date('Y-m-d', strtotime($is_valid->quotation_valid_date)))) {
                echo json_encode(array('response' => 'invalid', 'message' => 'Quotation Validity will be ended.'));

                exit();
            }
        }



        DB::beginTransaction();

        try {

            if ($is_valid->status < 5) {
                PurchaseRequest::where('id', '=', $pr_id)->update([
                    'status' => 5,
                ]);
            }



            for ($i = 0; $i < sizeof($item_ids); $i++) {
                $price = $vendor_prices[$i];

                $is_already = ComparativeStatement::getItemPrices($pr_id, $vendor_id, $item_ids[$i])['item'];

                if ($is_already == true && !empty($price)) {

                    ComparativeStatement::where('purchase_request_id', '=', $pr_id)
                        ->where('item_id', $item_ids[$i])
                        ->where('vendor_id', $vendor_id)
                        ->update([
                            'price' => $price,
                            'message' => $vendor_messages[$i],
                        ]);
                }


                if ($is_already == false) {

                    if (empty($price)) {
                        $price =  ItemPurchaseRequest::where('purchase_request_id', $pr_id)
                            ->where('item_id', $item_ids[$i])
                            ->first()
                            ->price;
                    }

                    ComparativeStatement::create([
                        'purchase_request_id' => $pr_id,
                        'item_id' => $item_ids[$i],
                        'vendor_id' => $vendor_id,
                        'price' => $price,
                        'message' => $vendor_messages[$i]

                    ]);
                }


                $purchase_order = PurchaseOrder::where('purchase_request_id', $pr_id)
                    ->where('vendor_id', $vendor_id)
                    ->first();

                if ($purchase_order == true) {
                    ItemPurchaseOrder::where('purchase_order_id', '=', $purchase_order->id)
                        ->where('item_id', $item_ids[$i])
                        ->update([
                            'price' => $price,
                        ]);
                }
            }



            for ($i = 0; $i < $file_length; $i++) {
                if ($request->file($i)) {
                    $imagePath = $request->file($i);
                    $imageExtension = $imagePath->getClientOriginalExtension();
                    if (!in_array($imageExtension, $supported_image)) {
                        echo json_encode(array('response' => 'invalid', 'message' => 'Only jpg|png|JPG|PNG|jpeg|gif|pdf|docx  Aceptable.'));
                        DB::rollback();
                        exit();
                    }
                    if (in_array($imageExtension, array('docx', 'pdf'))) {
                        $imageName = time() . '.' . $imagePath->getClientOriginalName();
                    } else {
                        $imageName = md5(time() . '.' . $imagePath->getClientOriginalName());
                    }
                    $path = $imagePath->storeAs('cs_document', $imageName, 'public');

                    ComparativeStatementDocument::create([
                        'pr_id' => $pr_id,
                        'vendor_id' => $vendor_id,
                        'document_name' => $imageName,
                    ]);
                }
            }



            DB::commit();

            echo json_encode(array('response' => 'yes', 'message' => 'Your CS sent successfully.'));
        } catch (\Exception $e) {
            DB::rollback();
        }
    }
    public function comparativeStatementViewApprovalPending($pr_id = null, Request $request)
    {


        if (is_numeric($pr_id)) {

            $total_cs = 0;
            $total_rfq = 0;
            $role = $request->input('user');
            $po = $request->input('po');

            $purchase_request = PurchaseRequest::with([
                'ItemPurchaseRequests',
                'comparativeStatements'
            ])
                ->whereHas('ItemPurchaseRequests', function ($query) use ($pr_id) {
                    $query->where('purchase_request_id', $pr_id);
                })
                ->whereHas('comparativeStatements', function ($query) use ($pr_id) {
                    $query->where('purchase_request_id', $pr_id);
                })
                ->withAndWhereHas('csApprovalStatus', function ($query) use ($role, $pr_id) {
                    $query->where('role_id', $role);
                    $query->where('approvel_status', 0);
                    $query->where('purchase_request_id', $pr_id);
                })->first();

            $purchase_request = json_decode(json_encode($purchase_request));

            if ($purchase_request->status > 3) {
                $total_rfq = $total_rfq = sizeof(json_decode($purchase_request->rfq_vendors));
            }

            if ($purchase_request->status > 4) {
                $total_cs = ComparativeStatement::getVendorIds($pr_id);
                $total_cs = sizeof($total_cs);
            }
            $roles = Role::orderBy('id', 'DESC')->get();

            $pending_approvals =  PurchaseOrder::where('purchase_request_id', '=', $pr_id)->where('status', 0)->get(['id']);

            return view('procurement/comparative-statement.pending-approval', compact('purchase_request', 'pending_approvals', 'total_cs', 'total_rfq', 'roles', 'role', 'po'));
        }
    }
    public function view($pr_id = null)
    {

        if (is_numeric($pr_id)) {

            $total_cs = 0;
            $total_rfq = 0;

            $purchase_request = PurchaseRequest::with([
                'ItemPurchaseRequests',
                'comparativeStatements',
                'department'
            ])
                ->whereHas('ItemPurchaseRequests', function ($query) use ($pr_id) {
                    $query->where('purchase_request_id', $pr_id);
                })
                ->whereHas('comparativeStatements', function ($query) use ($pr_id) {
                    $query->where('purchase_request_id', $pr_id);
                })->first();

            $purchase_request = json_decode(json_encode($purchase_request));



            if ($purchase_request->status > 3) {
                $total_rfq = $total_rfq = sizeof(json_decode($purchase_request->rfq_vendors));
            }

            if ($purchase_request->status > 4) {
                $total_cs = ComparativeStatement::getVendorIds($pr_id);
                $total_cs = sizeof($total_cs);
            }

            $roles = Role::orderBy('id', 'DESC')->get();

            $pending_approvals =  PurchaseOrder::where('purchase_request_id', '=', $pr_id)->where('status', 0)->get(['id']);


            return view('procurement/comparative-statement.view', compact('purchase_request', 'total_cs', 'total_rfq', 'roles', 'pending_approvals'));
        }
    }
    public function detail(Request $request)
    {

        $vendor_id = Crypt::decryptString($request->input('vendor'));
        $purchase_request_id = Crypt::decryptString($request->input('purchase_request'));

        $is_item_exist =  PurchaseOrder::where('purchase_request_id', '=', $purchase_request_id)->get();


        $purchase_request = PurchaseRequest::where('id', $purchase_request_id)
            ->first();

        $rfq_items = ItemVendor::getVendorItems($vendor_id, $purchase_request_id);

        $vendor = PurchaseRequestVendor::find($vendor_id);


        return view('procurement/request-for-quotation.cs-detail', compact('purchase_request', 'rfq_items', 'vendor', 'purchase_request_id', 'is_item_exist'));
    }
}
