<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\PurchaseOrder;
use App\ItemPurchaseOrder;
use App\ComparativeStatement;
use DB;
use App\ItemPurchaseRequest;
use App\PurchaseRequest;
use App\PurchaseRequestVendor;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Validator;
use App\ItemVendor;
use App\PurchaseOrderReceipt;
use App\Project;
use PDF;
use App\Item;
use Mail;
use App\Mail\RequestForQuotationMail;
use App\ReceiptItem;
use App\Expense;
use App\ChartOfAccount;
use App\Vendor;
use App\CsApproval;
use App\ApprovelStatus;
use App\PurchaseRequestBoqItem;
use App\PurchaseOrderRemark;
class PurchaseOrderController extends Controller
{

    public function __construct()
    {
               
    }

    public function index()
    {
        $purchase_requests = PurchaseRequest::orderBy('id', 'DESC')
        ->where([['status' ,'>', 5]])->get();
        return view('procurement/purchase-order.view' ,compact('purchase_requests') );
    }

    public function registerNewVendorAndSendRfq(Request $request)
    {
        $pr_id = $request->pr_id;
        $name = $request->name;
        $email = $request->email;
        $contact = $request->contact;
        $cnic = $request->cnic;
        $item_ids = $request->item_ids;
        $item_qty = $request->item_qty;
        $address = $request->address;
        $project_name = $request->project_name;
        $message = $request->message;
        $quotation_valid_date = $request->quotation_valid_date;

        $validator = Validator::make($request->all(), [
                'name' => 'required|unique:vendors,name',
                'email' => 'required|email',
                'contact' => 'required|unique:vendors,phone|numeric|min:11',  
                'pr_id' =>  'required',
                'cnic' => 'required',
                'project_name' => 'required',
                'quotation_valid_date' => 'required',
         ]);

        if ($validator->fails())
        {
          return response()->json($validator->messages(), 200);
        }


        if (in_array('0', $item_qty) || in_array('', $item_qty))
          {
            echo json_encode(array('quantity' => 'Invalid Item quantity'));
            exit();
          }

        

          $success = false;

    DB::beginTransaction();

    try {

        PurchaseRequest::where('id', '=', $pr_id)->update([
           
            'quotation_valid_date' => $quotation_valid_date,
            'quotation_created_date' => date('Y-m-d'),
            'note' => $message
          ]);

        $vendor = new Vendor;
        $vendor->name = $name;
        $vendor->email = $email;
        $vendor->phone = $contact;
        $vendor->cnic = $cnic;
        $vendor->address = $address;
        

        if ($vendor->save()) 
        {
            
             foreach ($item_ids as $key => $item) 
        {

             $qty = ItemPurchaseRequest::where('purchase_request_id' , $pr_id )->where('item_id' , $item)->first()->remaining_quantity;
            
            if($item_qty[$key] > $qty)
            {

                echo json_encode(array('quantity' => 'Items Quantity not greater than Request.'));
                DB::rollback();
                exit();
            }

             $vendor->items()->attach($item);
        }

            $success = true;
        }


        if($vendor)
        {
        $vendor_data = array('name' =>  $vendor->name , 'link' => url('request-for-quotations/rfq?vendor='.Crypt::encryptString($vendor->id).'&purchase_request='.Crypt::encryptString($pr_id).'')  , 'project_name' => $project_name);

        Mail::to($vendor->email)->send(new RequestForQuotationMail($vendor_data));
        }


        DB::commit();

         echo  json_encode(array('response' => 'send'));
      } 
        
        catch (\Exception $e) 
      {
       DB::rollback();
    
      }


    }


function sum_same($array) {

    $keyArray = [];

    foreach ($array as $entry) {
        $name = $entry["item_id"];
        if(isset($keyArray[$name])) {
            $keyArray[$name] += $entry["item_quantity"];
        } else {
            $keyArray[$name] = $entry["item_quantity"];
        }
    }

    // Convert the keyArray to the old format.
    $resultArray = [];
    foreach ($keyArray as $key => $value) {
        $resultArray[] = ["itemId" => $key, "itemQuantity" => $value];
    }

    return $resultArray;
}



    public function create(Request $request)
    {

        $pr_id = $request->pr_id;
        $items = $request->items;
        $delivery_date = $request->delivery_date;
        $special_ins = $request->special_ins;
        $roles = $request->roles;


        if(empty( $delivery_date) ||  strtotime( $delivery_date) < strtotime(date('Y-m-d')) )
        {
            echo json_encode(array('delivery_date_error' => true));
            exit();
        }

          if (empty( $roles )) 
        {
            echo json_encode(array('roles_error' => "Please Select  Role For Approval."));
             exit();
        }

        if(in_array(0, array_column($items, 'item_quantity')) || in_array('', array_column($items, 'item_quantity')))
        {
        echo json_encode(array('quantity' => 'Items Quantity Not Be Empty or Zero.'));
        exit();
        }
    
        $vendors = array_unique(array_column($request->items, 'item_vendor'));

        $vendorArray = array();

        foreach($vendors as $vendor)
        {
            $total_amount = 0;

              $vendor_name = Vendor::find($vendor)->name;

           foreach ($request->items as $key => $value) 
           {
               if ($value['item_vendor'] == $vendor) 
               {
                    $get_vendor_price = ComparativeStatement::where('purchase_request_id', '=', $pr_id)
                    ->where( 'vendor_id' , $vendor)
                    ->where( 'item_id' , $value['item_id'] )
                    ->first()
                    ->price;

                    $total_amount +=  $get_vendor_price * $value['item_quantity'];

               }
           }

            $vendorArray[] = array('vendor' =>  $vendor_name , 'vendor_id' =>  $vendor , 'amount' => number_format($total_amount , 2) );
    }

        $is_already_sent  =  PurchaseOrder::where('purchase_request_id', '=', $pr_id)
        ->whereIn( 'vendor_id' ,  $vendors )->count();


        if ($request->type == 'addAdvancePayment' && $is_already_sent == 0) 
        {
            echo json_encode(array('response' => 'addAdvancePayment' , 'total' =>  $vendorArray ));
            exit;
        }

        DB::beginTransaction();

        try {

        //.....................Create PO ANd Insert PO Items..................................

        $ItemArrayToSum  = array();
        $poArray = array();
        $response = 0;
        foreach ($items as $key => $item) 
        {

        $po = PurchaseOrder::where('purchase_request_id', '=', $pr_id)
        ->where( 'vendor_id' ,$item['item_vendor'] );

        $is_po_exist = $po->first();

        if($is_po_exist == true)
        {
            
            $purchase_order_id = $is_po_exist->id;
            $currentPOStatus = $is_po_exist->status;

            if(strtotime(date('Y-m-d' , strtotime( $is_po_exist->delivery_date))) > strtotime(date('Y-m-d')))
            {
                $po->update([
                  'delivery_date' => date('Y-m-d H:i:s' , strtotime($delivery_date)),
                ]);
            }

             if($currentPOStatus == 2)
            {
                $po->update([
                  'status' => 3,
                ]);
            }


            // if ($is_po_exist->advance > 0) 
            // {
            //     $po->update([
            //      'total_amount' =>   $is_po_exist->total_amount+ $total_amount,
            //     ]);

            //     $advanceAmount = ($total_amount*$is_po_exist->advance) / 100;

            //     $is_already_po_exist = PurchaseOrderReceipt::where([['purchase_order_id' , $is_po_exist->id] , ['vendor_id' , $is_po_exist->vendor_id] , ['purchase_request_id' , $is_po_exist->purchase_request_id] , ['receipt_type' , 2] ])->first();

            //     if ($is_already_po_exist == true ) 
            //     {
            //        $is_already_po_exist->update([
            //         'total_amount' => $is_already_po_exist->total_amount + $advanceAmount,
            //         'remaining_amount' => $is_already_po_exist->remaining_amount + $advanceAmount,
            //         ]);
            //     }

            // }
      
        }


        if($is_po_exist == false)
        {
            $advanceAmount = 0;
            $totalPercentage = 0;


            $purchase_order =  PurchaseOrder::create([
            'purchase_request_id' => $pr_id,
            'vendor_id' => $item['item_vendor'],
            'status' => 0,
            'delivery_date' => date('Y-m-d H:i:s' , strtotime($delivery_date) ),
            'special_ins' => $special_ins,
            ]);

            $response = 1;

            $purchase_order_id = $purchase_order->id;

            $poArray[] = array('po' => $purchase_order_id , 'vendor' => $item['item_vendor']) ;


            for ($i = 0; $i < sizeof($roles); $i++)
            { 
            CsApproval::create([
            'role_id' => $roles[$i],
            'purchase_request_id' => $pr_id,
            'purchase_order_id' => $purchase_order_id,
            'approvel_status' => 0,
            ]);

            $approval_status = new ApprovelStatus();
            $approval_status->pusherNotification($roles[$i], $pr_id);
            }

        }

        $get_vendor_price = ComparativeStatement::where('purchase_request_id', '=', $pr_id)
        ->where( 'vendor_id' , $item['item_vendor'])
        ->where( 'item_id' , $item['item_id'] )
        ->first()
        ->price;

         $item_purchase_request = ItemPurchaseRequest::where('purchase_request_id', '=', $pr_id)
        ->where( 'item_id' , $item['item_id'] );

       $get_requested_items =  $item_purchase_request->first();

       $remainingItemsQuantity = $get_requested_items->quantity;

        $totalSumOfItemQuantities  = $this->sum_same( $items);

        $totalItemremain = 0;

         for ($i=0; $i < sizeof($totalSumOfItemQuantities); $i++) 
         { 
            if($totalSumOfItemQuantities[$i]['itemId'] == $item['item_id'])
            {
                if($totalSumOfItemQuantities[$i]['itemQuantity'] > $remainingItemsQuantity)
                {
                    echo json_encode(array('quantity' => 'Quantity Not Be Greater Than Demand Quantity.'));
                    DB::rollback();
                    exit(); 
                }

               $totalItemremain = $totalSumOfItemQuantities[$i]['itemQuantity'];
                
            }
         }
 

        $item_purchase_order = ItemPurchaseOrder::where('purchase_request_id', '=', $pr_id)
        ->where( 'item_id' , $item['item_id'] )->where( 'purchase_order_id' , $purchase_order_id );

        $remainingItemsQuantity  = ($get_requested_items->remaining_quantity - $item['item_quantity']);


        if($item_purchase_order->first() == true)
        {
            $item_purchase_order->update([
            'demand_quantity' =>  $item['item_quantity'] + $item_purchase_order->first()->demand_quantity,
            ]);
        }

       if($item_purchase_order->first() == false)
        {
            ItemPurchaseOrder::create([
            'purchase_order_id' => $purchase_order_id,
            'purchase_request_id' => $pr_id,
            'item_id' => $item['item_id'],
            'price' =>  $get_vendor_price,
            'total_quantity' => $get_requested_items->quantity,
            'demand_quantity' =>  $item['item_quantity']
            ]);
        }


        $item_purchase_request->update([
        'remaining_quantity' => $remainingItemsQuantity ,
        ]);

        $pr_Boq_item = PurchaseRequestBoqItem::where([['purchase_request_id' , $pr_id] , ['item_id' , $item['item_id']]]);

        if ($pr_Boq_item->first() == true) 
        {
              $quantity = $pr_Boq_item->first()->quantity;

              $pr_Boq_item->update([
                  'rate_per_unit' =>  $get_vendor_price,
                  'total_cost' => $get_vendor_price * $quantity,
                ]);
        }
      

       if($item_purchase_request->first()->remaining_quantity < 0 )
        {
            echo json_encode(array('quantity' =>  'Quantity Not Be Greater Than Remaining Quantity.'));
            DB::rollback();
            exit(); 
        }

    }



        if ($response == 1) 
        {

            foreach($poArray as $poList)
            {
                     foreach($request->vendor_per as $vendor_advance)
                {
                    if ($vendor_advance['advance_percentage'] > 0 && $vendor_advance['vendor_id'] == $poList['vendor']) 
                    {
                        $advanceAmount = str_replace(',' , '' , $vendor_advance['amount']);
                        $totalPercentage = $vendor_advance['advance_percentage'];

                        PurchaseOrder::where('id' , $poList['po'])->update([
                        'advance' => $totalPercentage,
                        'total_amount' => $advanceAmount,
                        ]);
                    }
                }
            }
        }

         DB::commit();
        
         echo json_encode(array('response' => 'yes'));
       
      } 
        catch (\Exception $e) 
      {
        DB::rollback();

        dd($e);
      }
    }

    public function view($pr_id)
    {
        if(is_numeric($pr_id))
        {
            $po_vendors = PurchaseOrder::where('purchase_request_id' , $pr_id)
            ->where('status' , '!=' , 0)->pluck('vendor_id')->toArray();
            $vendors = PurchaseRequestVendor::whereIn('id' , $po_vendors)->get();
            return view('procurement/purchase-order.po-list',compact('vendors','pr_id'));
        }
    }

    public function detail( Request $request)
    {

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

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

        $purchase_order = PurchaseOrder::with(['purchaseOrderItems'])->where('vendor_id' ,  $vendor_id ) ->where('purchase_request_id' , $purchase_request_id)->first();
        $po_items = PurchaseOrder::find( $purchase_order->id )->purchaseOrderItems;

        $po_receipts = $purchase_order->purchaseOrderReceipts;
        $purchase_order = json_decode(json_encode($purchase_order));
         

        foreach($purchase_order->purchase_order_items as  $list)
        {
            if ($purchase_order->status != 1 && ($list->demand_quantity > $list->received_quantity)) 
            {
                $remaing ++;
            }
        }


        $vendor = PurchaseRequestVendor::find( $vendor_id );
        
          $project = Project::withTrashed()->find(!empty($purchase_request)?$purchase_request->project_id:null);
        
       
        return view('procurement/purchase-order.index' , compact('purchase_request' , 'po_items' , 'vendor' , 'purchase_request_id' , 'purchase_order' , 'project' , 'remaing' , 'po_receipts' ) );
    }

    public function validatePurchaseOrder(Request $request)
    {
        $pr_id = $request->pr_id;
        $vendor_id = $request->vendor_id;
        $item_ids = explode(',' , $request->item_ids);
        $po_item_qty = explode(',' , $request->po_item_qty);
        $receiver_name = $request->receiver_name;
        $file_length = $request->file_length;

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

       $images = array();

       
        if( empty($receiver_name))
        {
              echo json_encode(array('response' => 'invalid_receiver_name'));
              exit();
        }


         if(empty( $file_length) &&  !$file_length > 0)
        {
            echo json_encode(array('response' => 'invalid_document' , 'message' => 'Please Select Documents to upload.'));
              exit();
        }

        
        DB::beginTransaction();

        try {

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

            $purchase_request = PurchaseRequest::find($pr_id);
            $status = 'po_receive';
            $remaining_quantity = 0;


                PurchaseOrder::where('id', '=', $purchase_order->id)
                ->update([
                'status' => 2,
                ]);

        

              $po_receipt =   PurchaseOrderReceipt::create([
                'purchase_order_id' => $purchase_order->id,
                'purchase_request_id' => $pr_id,
                'vendor_id' => $vendor_id,
                'receipt_date' => date('Y-m-d H:i:s'),
                 'status' => 3,
              ]);

              


          $total_price = 0;

           for ($item = 0; $item < sizeof($item_ids); $item ++) 
          { 

            if(!empty($po_item_qty[$item]))
            {
              $receive_qty = $po_item_qty[$item];
            }

            $item_purchase_order= ItemPurchaseOrder::where('purchase_order_id', '=', $purchase_order->id)->where('purchase_request_id', '=', $pr_id)->where('item_id' , $item_ids[$item] );

            $original_qty =$item_purchase_order->first()->demand_quantity;

            if(empty(trim($po_item_qty[$item])))
            {
              $receive_qty = $original_qty;
            }
        
          
              if(trim($po_item_qty[$item]) == '0' )
            {
                 echo json_encode(array('response' => 'invalid_qty'));
                 DB::rollback();
                 exit();
            }

             if(!empty(trim($po_item_qty[$item])) && trim($po_item_qty[$item]) < '0')
            {
                 echo json_encode(array('response' => 'invalid_qty'));
                 DB::rollback();
                 exit();
            }  
            
           
            $data = [
            'received_quantity' => $receive_qty,
            'remaining_quantity' => $remaining_quantity ,
            ];


            if($receive_qty < $original_qty)
            {
                 $status = 'po_partial_receive';
                 $data['remaining_quantity'] = $original_qty - $receive_qty;
            }


            if($receive_qty > $original_qty)
            {
                echo json_encode(array('response' => 'invalid_qty'));
                DB::rollback();
                exit();
            }

            $item_purchase_order->update($data);


            $total_price += ($receive_qty  * $item_purchase_order->first()->price);

            

            ReceiptItem::create([
            'purchase_order_id' => $purchase_order->id,
            'purchase_request_id' => $pr_id,
            'purchase_order_receipt_id' => $po_receipt->id,
            'vendor_id' => $vendor_id,
            'item_id' => $item_ids[$item], 
            'quantity' => $receive_qty,
            ]);


           }

       
//////////////Images Upload Section ////////////////////////////////


            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_document' , '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('uploads', $imageName, 'public');
            $images[] = $imageName;
            }
            }


           

              $is_first = PurchaseOrderReceipt::where('purchase_order_id' , $purchase_order->id)->where('receipt_type' , 1)->count();

                $data =  [
                'total_amount' =>  $total_price,
                'documents' => json_encode($images),
                'po_receiver_name' => $receiver_name,
                'po_receiveing_date' => date('Y-m-d H:i:s'),
                ];

                 $remainingPrice = $total_price;

                if ($is_first == 1) 
                {
                $advanceAmount = ( $purchase_order->total_amount*$purchase_order->advance) / 100;
                
                $data['total_pay_amount'] = $advanceAmount;
                $remainingPrice = $remainingPrice - $advanceAmount;
                }

                $data['remaining_amount'] = $remainingPrice;

                $po_receipt =  PurchaseOrderReceipt::where('id' ,  $po_receipt->id )->update($data);



            if($status == 'po_partial_receive')
            {
                $po_updates['status'] = 3;
                PurchaseOrder::where('vendor_id' ,  $vendor_id )
                ->where('purchase_request_id' , $pr_id)
                ->update( $po_updates );
            }

          DB::commit();
        
          echo json_encode(array('response' => 'yes'));
      
      } 
        
        catch (\Exception $e) 
      {
        DB::rollback();
         
      }
    }

    public function validateRemainingPurchaseOrder(Request $request)
    {
        $pr_id = $request->pr_id;
        $vendor_id = $request->vendor_id;
        $item_ids = explode(',' , $request->item_ids);
        $po_item_qty = explode(',' , $request->po_item_qty);
        $total_price = 0;

         $file_length = $request->file_length;

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

        $images = array();

        $receiver_name = $request->remain_order_receiver_name;

        if(!ctype_alpha($receiver_name)  || empty($receiver_name))
        {
              echo json_encode(array('response' => 'invalid_receiver_name'));
              exit();
        }

        DB::beginTransaction();

        try {

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

            $purchase_request = PurchaseRequest::find($pr_id);
            $status = 'po_receive';
            $remaining_quantity = 0;


                PurchaseOrder::where('id', '=', $purchase_order->id)
                ->update([
                'status' => 2,
                ]);

              

              $po_receipt = PurchaseOrderReceipt::create([
                'purchase_order_id' => $purchase_order->id,
                'purchase_request_id' => $pr_id,
                'vendor_id' => $vendor_id,
                'receipt_date' => date('Y-m-d H:i:s'),
                'status' => 3,
              ]);

              //Nadeem


           for ($item = 0; $item < sizeof($item_ids); $item ++) 
          { 

           $purchase_order_item =ItemPurchaseOrder::where('purchase_order_id', '=', $purchase_order->id)->where('item_id' , $item_ids[$item] )->where('purchase_request_id', '=', $pr_id);


            if(!empty($po_item_qty[$item]))
            {

            $receive_qty = ($po_item_qty[$item] + $purchase_order_item->first()->received_quantity);
            } 

           $original_qty =$purchase_order_item->first()->demand_quantity;


            if(empty(trim($po_item_qty[$item])))
            {
              $receive_qty = $original_qty;
            }
          
              if(trim($po_item_qty[$item]) == '0' )
            {
                 echo json_encode(array('response' => 'invalid_qty'));
                 DB::rollback();
                 exit();
            }

             if(!empty(trim($po_item_qty[$item])) && trim($po_item_qty[$item]) < '0')
            {
                 echo json_encode(array('response' => 'invalid_qty'));
                 DB::rollback();
                 exit();
            } 



            $data = [
            'received_quantity' => $receive_qty,
            'remaining_quantity' => $remaining_quantity ,
            ];


            if($receive_qty < $original_qty)
            {
                 $status = 'po_partial_receive';
                 $data['remaining_quantity'] = $original_qty - $receive_qty;
            }


            if($receive_qty > $original_qty)
            {
                 echo json_encode(array('response' => 'invalid_qty'));
                 DB::rollback();
                 exit();
            }

            $total_receive_qty = $po_item_qty[$item];

            if (empty($total_receive_qty)) 
            {
               $total_receive_qty = $purchase_order_item->first()->remaining_quantity;
            }
            
           $purchase_order_item->update($data);


             $total_price  +=  ($purchase_order_item->first()->price * $total_receive_qty);

               ReceiptItem::create([
                'purchase_order_id' => $purchase_order->id,
                'purchase_request_id' => $pr_id,
                'purchase_order_receipt_id' => $po_receipt->id,
                'vendor_id' => $vendor_id,
                'item_id' => $item_ids[$item], 
                'quantity' => $total_receive_qty,
              ]);

           }

           //Nadeem
        //       $expense = Expense::create([
        //         'vendor_id' => $vendor_id,
        //         'category_id' => 8,
        //         'amount' => $total_price,
        //         'billed_at' => date('Y-m-d'),
        //         'due_at' => date('Y-m-d'),
        //         'status' => 0 ,
        //         'expense_type' => Expense::CONSTRUCTION


        //       ]);

        //       //add general entry
        // $debitAccount = ChartOfAccount::where('id',8)->first()->name;
        // $vendor = Vendor::find($vendor_id);
        
        // UtilsController::addGeneralEntry($debitAccount,'(A/P) Accounts Payable',$total_price,'',$vendor->id,2,date('Y-m-d'),'Bill');

           //////////////Images Upload Section ////////////////////////////////


            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_document' , '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('uploads', $imageName, 'public');
              $images[] = $imageName;
             }
        }
             

            $is_first = PurchaseOrderReceipt::where('purchase_order_id' , $purchase_order->id)->where('receipt_type' , 1)->count();

                $data =  [
                'total_amount' =>  $total_price,
                'documents' => json_encode($images),
                'po_receiver_name' => $receiver_name,
                'po_receiveing_date' => date('Y-m-d H:i:s'),
                ];

                   $remainingPrice = $total_price;

                if ($is_first == 1) 
                {
                $advanceAmount = ( $purchase_order->total_amount*$purchase_order->advance) / 100;
                
                $data['total_pay_amount'] = $advanceAmount;
                $remainingPrice = $total_price - $advanceAmount;
                }

                  $data['remaining_amount'] = $remainingPrice;

                $po_receipt =  PurchaseOrderReceipt::where('id' ,  $po_receipt->id )->update($data);


           if($status == 'po_partial_receive')
           {
                $po_updates['status'] = 3;
                PurchaseOrder::where('vendor_id' ,  $vendor_id )
                ->where('purchase_request_id' , $pr_id)
                ->update( $po_updates );
           }

           

            DB::commit();
        
            echo json_encode(array('response' => 'yes'));
      
      } 
        
        catch (\Exception $e) 
      {
        DB::rollback();
     
      }
    }

    public function cancelPurchaseOrder(Request $request)
    {
        $po_id = $request->po_id;
        $po_remarks = $request->po_remarks;
        $pr_id = $request->pr_id;


         $purchase_order = ItemPurchaseOrder::where('purchase_order_id', '=', $po_id)->get();
         DB::beginTransaction();

        try {

            foreach ($purchase_order as $key => $list)

            {
              $item_purchase_request =  ItemPurchaseRequest::where('purchase_request_id' , $list->purchase_request_id)->where('item_id' , $list->item_id);

               $item_purchase_request->update([
                    'remaining_quantity' => ($list->demand_quantity +  $item_purchase_request->first()->remaining_quantity)
                ]);  

            } 

                $purchase_order = PurchaseOrder::where('id' ,  $po_id);
                $vendor_id = $purchase_order->first()->vendor_id;

                ItemPurchaseOrder::where('purchase_order_id' ,  $po_id)->delete();
                CsApproval::where('purchase_order_id' ,  $po_id)->delete();

                PurchaseOrderRemark::create([
                'pr_id' =>   $pr_id,
                'po_id' =>   $po_id,
                'remark' =>   $po_remarks,
                'vendor_id' => $vendor_id,
                ]);

                $purchase_order->delete();

              DB::commit();
        
            return redirect()->back()->with('success' , 'Purchase Order Cancel Successfully');      
      } 
        
        catch (\Exception $e) 
      {
        DB::rollback();

        return redirect()->back()->with('error' , 'Something went wrong Please try again.'); 
      }
     
    }

    public function vendorPurchaseOrder(Request $request)
    {
        $vendorId = $request->input('vendor');
        $status = $request->input('status');

        if($status  == 'po-sent')
        {
        $status = 1;  
        }

        if($status  == 'po-receive')
        {
        $status = 2;  
        }

        if($status  == 'po-partial-receive')
        {
        $status = 3;  
        }

        $vendor_po = PurchaseOrder::where('vendor_id' , $vendorId )->where('status' , $status)->orderBy('created_at', 'DESC')->get();
        $vendor = PurchaseRequestVendor::find($vendorId);
        return view('procurement/purchase-order.vendor-po-list' , compact('vendor_po' , 'vendor' ));
    }

    public function listPurchaseOrder(Request $request)
    {
        $status = $request->input('status');

        if($status  == 'po-sent')
        {
          $status = 1;  
        }

        if($status  == 'po-receive')
        {
          $status = 2;  
        }

        if($status  == 'po-partial-receive')
        {
          $status = 3;  
        }

      
        $total_purchase_orders  = PurchaseRequest::withAndWhereHas('PurchaseOrders', function($query) use ($status)
        {
        $query->where('status',  $status);
        })
        ->where('department_id' , $request->department )
        ->get();
        $total_purchase_orders = json_decode(json_encode($total_purchase_orders));
        return view('procurement/purchase-order.all' , compact('total_purchase_orders') );

    }

    public function quanlityTest(Request $request)
    {
        $pr_id = $request->pr_id;
        $vendor_id = $request->vendor_id;
        $item_id = $request->item_id;
        $item_quantity = $request->item_quantity;
        $receiver_name = $request->receiver_name;
        $quality_number = $request->quality_number;
        $receipt_id = $request->receipt_id;
        $note = $request->note;
        $type = $request->type;

        if(empty($receiver_name))
        {
              
              echo json_encode(array('response' => 'invalid' , 'message' => 'Please Input Valid Name.'));
              exit();
        }

         if(empty($quality_number) || !is_numeric($quality_number))
        { 
              echo json_encode(array('response' => 'invalid' , 'message' => 'Please Input Valid Quantity In Numbers.'));
              exit();
        }

        DB::beginTransaction();

        try {

            $purchase_request = PurchaseRequest::find($pr_id);

          if ( $type == 'pass') 
            {
                $current_item = Item::where('id' , $item_id);
                $quantity = ($current_item->first()->quantity + $quality_number);
                $current_item->update(['quantity' => $quantity]);
            }

            $receipt_item = ReceiptItem::where('purchase_request_id' ,  $pr_id )
            ->where('vendor_id' ,  $vendor_id )
            ->where('purchase_order_receipt_id' ,  $receipt_id )
            ->where('item_id' , $item_id);
            
            $quantity_check = $receipt_item->first();
            $remainingQuantity = $quantity_check->quantity - ($quantity_check->pass_quantity + $quantity_check->fail_quantity);

            if ( $quality_number > $remainingQuantity)
            {
                DB::rollback();
                echo json_encode(array('response' => 'invalid' , 'message' => 'Quantity not be greater than original quantity. You have only '.$remainingQuantity.' Left For Test. '));
                exit();
            }
            
            $data = [
            'quality_test_approve_by' =>  $receiver_name ,
            'approval_date' =>  date('Y-m-d H:i:s'),
            'approval_status' => 'approve'
            ];

            if(!empty($note))
            {
              $data['note'] = $note;
            }
            
            if($type == 'pass')
            {
              $data['pass_quantity'] =  $quality_number + $quantity_check->pass_quantity;
            }

             if($type == 'fail')
            {
              $data['fail_quantity'] =  $quality_number + $quantity_check->fail_quantity;
            }

            $receipt_item->update($data);

            $check = ReceiptItem::where('purchase_request_id' ,  $pr_id )
            ->where('vendor_id' ,  $vendor_id )
            ->where('purchase_order_receipt_id' ,  $receipt_id )
            ->get();

             $qualityStatus = array();
             $total_price  = 0;

            foreach ($check as $key => $list)
            {
               $item_price =  ItemPurchaseOrder::where('purchase_request_id' ,  $pr_id )->where('item_id' , $list->item_id)->where('purchase_order_id' , $list->purchase_order_id)->first()->price;

               $total_price  += ($item_price *  $list->pass_quantity);

               $qualityStatus[] = $list->approval_status;
            }

            $quantity_check = $receipt_item->first();
            $remainingQuantity = $quantity_check->quantity - ($quantity_check->pass_quantity + $quantity_check->fail_quantity);


             $is_first = PurchaseOrderReceipt::where('purchase_request_id' , $pr_id)->where('vendor_id' , $vendor_id)->where('receipt_type' , 1)->count();
            
$array = array();

           if (!in_array(null, $qualityStatus) && $remainingQuantity <= 0 ) 
           {

            PurchaseRequest::where('id', '=', $pr_id)->update([
            'status' => 7,
            ]);

            $array['status'] = 0;
           }
           else
           {
            $array['status'] = 3;
           }

           if ($is_first > 1) 
           {
            $array['total_amount'] = $total_price ;
            $array['remaining_amount'] = $total_price ;
           }



            PurchaseOrderReceipt::where('id' ,  $receipt_id )->update($array);


             if($type == 'fail')
            {
                $item_purchase_order = ItemPurchaseOrder::where('purchase_request_id' ,  $pr_id )->where('item_id' , $list->item_id)->where('purchase_order_id' , $quantity_check->purchase_order_id)
                ->first();

                ItemPurchaseOrder::where('purchase_request_id' ,  $pr_id )->where('item_id' , $list->item_id)->where('purchase_order_id' , $quantity_check->purchase_order_id)
                ->update([
                'received_quantity' =>  $item_purchase_order->received_quantity - $quality_number,
                ]);

                $purchase_order = PurchaseOrder::with(['purchaseOrderItems'])->where('id' , $quantity_check->purchase_order_id)->first();

                $purchase_order = json_decode(json_encode($purchase_order));

                foreach($purchase_order->purchase_order_items as  $list)
                {
                    if ($purchase_order->status != 1 && ($list->demand_quantity > $list->received_quantity)) 
                    {
                         PurchaseOrder::where('id' , $quantity_check->purchase_order_id)->update([ 'status' => 3]);
                         break;
                    }
                }

            }

          DB::commit();

          echo json_encode(array('response' => 'yes'));

      } 

        catch (\Exception $e) 
      {
        DB::rollback();
       
      }
    }

    public function uploadQuanlityTestDocs(Request $request)
    {

        $file_length = $request->file_length;
        $receipt_id = $request->receipt_id;

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

       $images = array();

      if(empty( $file_length) &&  !$file_length > 0)
        {
            echo json_encode(array('response' => 'invalid_document' , 'message' => 'Please Select Documents to upload.'));
              exit();
        }


 DB::beginTransaction();

        try {

    //////////////Images Upload Section ////////////////////////////////

            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_document' , '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('quality_documents', $imageName, 'public');
            $images[] = $imageName;
            }
            }

           //////////////Images Upload END////////////////////////////////


             PurchaseOrderReceipt::where('id' ,  $receipt_id )->update([
            'quality_insu_docs' =>  json_encode($images),
            ]);


              DB::commit();
        
          echo json_encode(array('response' => 'yes'));
      
      } 
        
        catch (\Exception $e) 
      {
        DB::rollback();
       echo json_encode(array('response' => 'invalid_document' , 'message' => 'Something went wrong. Please Refresh the page.'));
      }
    }

public function addMirDetail(Request $request)
{
    $inspector_name = $request->inspector_name;
    $vendor_tc = $request->vendor_tc;
    $receipt_id = $request->receipt_id;
    $vendor_id = $request->vendor_id;
    $type = $request->type;
    $invoice = $request->invoice;

    if ($type == 'inspector' && empty($inspector_name)) 
    {
       echo json_encode(array('response' => 'invalid' , 'message' => 'Please Input Valid Values.'));
       exit();
    }


     if ($type == 'invoice' && empty($invoice)) 
    {
       echo json_encode(array('response' => 'invalid' , 'message' => 'Please Input Valid Values.'));
       exit();
    }

     if ($type == 'vendor_tc' && empty($vendor_tc)) 
    {
       echo json_encode(array('response' => 'invalid' , 'message' => 'Please Input Valid Values.'));
       exit();
    }

       DB::beginTransaction();

        try {

            if ($type == 'invoice')
            {
                PurchaseOrderReceipt::where('id' ,  $receipt_id )->update([
                'invoice_no' =>  $invoice,
                ]); 
            }

             if ($type == 'inspector')
            {
                PurchaseOrderReceipt::where('id' ,  $receipt_id )->update([
                'quality_test_inspector_name' =>  $inspector_name,
                'quality_test_inspector_date' => date('Y-m-d H:i:s')
                ]); 
            }

            if ($type == 'vendor_tc')
            {
                 PurchaseRequestVendor::where('id' ,  $vendor_id )->update([
                 'test_certificate' =>  $vendor_tc,
                 ]); 
            }
            
            DB::commit();
            echo json_encode(array('response' => 'yes'));
      } 
        catch (\Exception $e) 
      {
        DB::rollback();
      }
}

public function add_cs_officers(Request  $request)
{
    $pr_id = $request->purchase_request_id;
    $status = $request->status;
    $manager_name = $request->manager_name;
    $officer_name = $request->officer_name;
    
    
    if($status  == 'officers')
    {
    if ( empty($officer_name)) 
    {
     echo json_encode(array('response' => 'invalid' , 'message' => "Please Enter Name!" ));
     exit;
    }
      $data = ['cs_purchase_officer' =>  $officer_name , 'cs_purchase_officer_date' => date('Y-m-d H:i:s') ];
    }

    if($status  == 'manager')
    {
         if ( empty($manager_name)) 
    {
         echo json_encode(array('response' => 'invalid' , 'message' => "Please Enter Name!" ));
         exit;
    }
      $data = ['cs_purchase_manager' =>  $manager_name , 'cs_purchase_manager_date' => date('Y-m-d H:i:s') ];
    }

    DB::beginTransaction();

    try 
    {
        PurchaseRequest::where('id' ,  $pr_id )->update( $data ); 
        DB::commit();
        echo json_encode(array('response' => 'yes'));
    } 
    catch (\Exception $e) 
    {
        DB::rollback();
    }

}

public function update_po_description(Request $request)
{
     $po_id = $request->po_id;
   
    $special_description = $request->special_description;
   
         if ( empty($special_description)) 
    {
         echo json_encode(array('response' => 'invalid' , 'message' => "Please Enter Valid Description!" ));
         exit;
    }

    $data = ['payment_terms' =>  $special_description ];
  
    DB::beginTransaction();

    try 
    {
        PurchaseOrder::where('id' ,  $po_id )->update( $data ); 
        DB::commit();
        echo json_encode(array('response' => 'yes'));
    } 
    catch (\Exception $e) 
    {
        DB::rollback();
    }
}

}