<?php

namespace Modules\Admin\Http\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Database\QueryException;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Carbon\Carbon;


use App\Models\User;
use App\Models\AdminDetails;
use App\Models\Companies;
use App\Models\Supliers;
use App\Models\Categories;
use App\Models\Brands;
use App\Models\Products;
use App\Models\ProductGallery;
use App\Models\GRNS;
use App\Models\Batches;
use App\Models\Returns;
use App\Models\Stock;
use App\Models\GRNProducts;

use File;
use Mail;
use Image;
use PDF;
class GRNController extends Controller
{
    public function add_grn(Request $request)
    { if($request->isMethod('get')){
        $supliers = Supliers::where('status','active')->get();
        $products = Products::where('status','active')->get();
        // $grnNumber = $this->generateUniqueGrnNumber();
        return view('admin::grn.add_grn',['supliers' => $supliers,'products' => $products]);
    }
    if($request->isMethod('post')){

        $request->validate([
            // 'grn_number'   => 'required',
            'suplier'   => 'required',
            'received_date'   => 'required',
            'invoice_no'   => 'required',
            'invoice_value'   => 'required',
            'purchase_order_number'   => 'required',
        ]);
        $grnNumber = $this->generateUniqueGrnNumber();
        $grn = new GRNS();
        $grn->grn_number =$grnNumber;
        $grn->suplier = $request->suplier;
        $grn->purchase_order_number = $request->purchase_order_number;
        $grn->received_date = $request->received_date;
        $grn->invoice_no = $request->invoice_no;
        $grn->invoice_value = $request->invoice_value;
        $grn->total_grn_cost = $request->total_grn_cost_input;
        $grn->save();


        $batches = $request->input('batches');

        foreach ($batches as $batch) {
            if(Batches::where("id", $batch['batch_id'])->exists()){
                
                $stock = new Stock();
                $stock->grn_id =  $grn->id;
                $stock->batch =  $batch['batch_id'];
                $stock->product = $batch['product_id'];
                $stock->initial_stock = $batch['qty'];
                $stock->avilable_stock = $batch['qty'];
                $stock->cost = $batch['cost'];
                $stock->is_free = 0;
                $stock->total_cost = $batch['total_cost'];
                $stock->save();

                if($batch['free_qty'] > 0){
                    $stock = new Stock();
                    $stock->grn_id =  $grn->id;
                    $stock->batch =  $batch['batch_id'];
                    $stock->product = $batch['product_id'];
                    $stock->initial_stock = $batch['free_qty'];
                    $stock->avilable_stock = $batch['free_qty'];
                    $stock->cost = 0;
                    $stock->is_free = 1;
                    $stock->total_cost = 0;
                    $stock->save();
                }

            }
            else{
                $batch_add = new Batches();
                $batch_add->batch =$batch['batch_id'];
                $batch_add->mrp =$batch['mrp'];
                $batch_add->expire_date =$batch['expire_date'];
                $batch_add->save();

                $stock = new Stock();
                $stock->grn_id =  $grn->id;
                $stock->batch =  $batch_add->id;
                $stock->product = $batch['product_id'];
                $stock->initial_stock = $batch['qty'];
                $stock->avilable_stock = $batch['qty'];
                $stock->cost = $batch['cost'];
                $stock->is_free = 0;
                $stock->total_cost = $batch['total_cost'];
                $stock->save();


                if($batch['free_qty'] > 0){
                    $stock = new Stock();
                    $stock->grn_id =  $grn->id;
                    $stock->batch =  $batch_add->id;
                    $stock->product = $batch['product_id'];
                    $stock->initial_stock = $batch['free_qty'];
                    $stock->avilable_stock = $batch['free_qty'];
                    $stock->cost = 0;
                    $stock->is_free = 1;
                    $stock->total_cost = 0;
                    $stock->save();
                }
            }
           
    
        }

        return back()->with('success', 'GRN Successfully Added');

    }

    }
    public function grns(Request $request)
    { if($request->isMethod('get')){
        $grns = GRNS::get();
        return view('admin::grn.grns',['grns' => $grns]);
    }

    }
    public function edit_grn($id,Request $request)
    {
    if($request->isMethod('get')){
    $grn_details = GRNS::where('id',$id)->first();
    $supliers = Supliers::where('status','active')->get();
    $products = Products::where('status','active')->get();
    $grn_products= Stock::where('grn_id', $id)->where('is_free', 0)->get();
    return view('admin::grn.edit_grn', ['grn_details' => $grn_details,'supliers' => $supliers,'products' => $products,'grn_products' => $grn_products]);
    }
    if($request->isMethod('post')){

        $grn = GRNS::find($id);
        $grn->suplier = $request->suplier;
        $grn->purchase_order_number = $request->purchase_order_number;
        $grn->received_date = $request->received_date;
        $grn->invoice_no = $request->invoice_no;
        $grn->invoice_value = $request->invoice_value;
        $grn->total_grn_cost = $request->total_grn_cost_input;
        $grn->update();

        $c=0;
        $batches = $request->input('batches');
        if($batches){
        foreach ($batches as $batch) {
            if(Batches::where("id", $batch['batch_id'])->exists()){
                $batch_details = Batches::where("id", $batch['batch_id'])->first();

                $batch_add = new Batches();
                $batch_add->batch =$batch_details->batch;
                $batch_add->mrp =$batch['mrp'];
                $batch_add->expire_date =$batch['expire_date'];
                $batch_add->save();
                
                $stock = new Stock();
                $stock->grn_id =  $id;
                $stock->batch =  $batch_add->id;
                $stock->product = $batch['product_id'];
                $stock->initial_stock = $batch['qty'];
                $stock->avilable_stock = $batch['qty'];
                $stock->cost = $batch['cost'];
                $stock->is_free = 0;
                $stock->total_cost = $batch['total_cost'];
                $stock->save();

                if($batch['free_qty'] > 0){
                    $stock = new Stock();
                    $stock->grn_id =  $id;
                    $stock->batch =  $batch_add->id;
                    $stock->product = $batch['product_id'];
                    $stock->initial_stock = $batch['free_qty'];
                    $stock->avilable_stock = $batch['free_qty'];
                    $stock->cost = 0;
                    $stock->is_free = 1;
                    $stock->total_cost = 0;
                    $stock->save();
                }

            }
            else{
                $batch_add = new Batches();
                $batch_add->batch =$batch['batch_id'];
                $batch_add->mrp =$batch['mrp'];
                $batch_add->expire_date =$batch['expire_date'];
                $batch_add->save();

                $stock = new Stock();
                $stock->grn_id =  $id;
                $stock->batch =  $batch_add->id;
                $stock->product = $batch['product_id'];
                $stock->initial_stock = $batch['qty'];
                $stock->avilable_stock = $batch['qty'];
                $stock->cost = $batch['cost'];
                $stock->is_free = 0;
                $stock->total_cost = $batch['total_cost'];
                $stock->save();


                if($batch['free_qty'] > 0){
                    $stock = new Stock();
                    $stock->grn_id =  $id;
                    $stock->batch =  $batch_add->id;
                    $stock->product = $batch['product_id'];
                    $stock->initial_stock = $batch['free_qty'];
                    $stock->avilable_stock = $batch['free_qty'];
                    $stock->cost = 0;
                    $stock->is_free = 1;
                    $stock->total_cost = 0;
                    $stock->save();
                }
            }
        }
    
        }
        return back()->with('success', 'GRN Details Successfully  Updated');
    }

    }
    public function add_return(Request $request)
    { if($request->isMethod('get')){
        return view('admin::grn.add_return');
    }
    if($request->isMethod('post')){
        $request->validate([
            'grn_number'   => 'required',
            'quantity'   => 'required',
            'return_date'   => 'required',
        ]);

        if(GRNS::where("grn_number",$request->grn_number)->exists()){

            $return = new Returns();
            $return->grn_number =$request->grn_number;
            $return->quantity = $request->quantity;
            $return->return_reason = $request->return_reason;
            $return->return_date = $request->return_date;
            $return->authorized_by = $request->authorized_by;
            $return->save();
    
            $current_quantity = GRNS::where('grn_number',$request->grn_number)->value('quantity');
            $grn = GRNS::where('grn_number',$request->grn_number)->first();
            $grn->quantity = $current_quantity-$request->quantity;
            $grn->update();

            return back()->with('success', 'GRN Successfully Added');
        }
        else{
            return back()->with('fail', 'Invalid GRN Number');
        }


    }

    }
    public function returns(Request $request)
    { if($request->isMethod('get')){
        $returns = Returns::get();
        return view('admin::grn.returns',['returns' => $returns]);
    }

    }
    public function edit_return($id,Request $request)
    {
    if($request->isMethod('get')){
    $return_details = Returns::where('id',$id)->first();
    return view('admin::grn.edit_return', ['return_details' => $return_details]);
    }
    if($request->isMethod('post')){
        $request->validate([
            'grn_number'   => 'required',
            'quantity'   => 'required',
            'return_date'   => 'required',
        ]);

        if(GRNS::where("grn_number",$request->grn_number)->exists()){

            $current_return_quantity = Returns::where('id',$id)->value('quantity');
            if($current_return_quantity > $request->quantity){

                $diff = $current_return_quantity - $request->quantity;
                $current_quantity = GRNS::where('grn_number',$request->grn_number)->value('quantity');
                $grn = GRNS::where('grn_number',$request->grn_number)->first();
                $grn->quantity = $current_quantity-$diff;
                $grn->update();

            }
            else if($current_return_quantity < $request->quantity){
                $diff = $request->quantity - $current_return_quantity;
                $current_quantity = GRNS::where('grn_number',$request->grn_number)->value('quantity');
                $grn = GRNS::where('grn_number',$request->grn_number)->first();
                $grn->quantity = $current_quantity+$diff;
                $grn->update();
            }
            else{

            }

            $return = Returns::where('id',$id)->first();
            $return->grn_number =$request->grn_number;
            $return->quantity = $request->quantity;
            $return->return_reason = $request->return_reason;
            $return->return_date = $request->return_date;
            $return->authorized_by = $request->authorized_by;
            $return->update();

            return back()->with('success', 'GRN Successfully Added');
        }
        else{
            return back()->with('fail', 'Invalid GRN Number');
        }
    }

    }
    public function get_all_batches($product_id)
    {
        $batches = Stock::where('product', $product_id)
                        ->select('batch')
                        ->distinct()
                        ->pluck('batch');
    
        $batchDetails = [];
    
        foreach ($batches as $batch) {
            $batchInfo = Batches::where('id', $batch)->first();
    
            if ($batchInfo) {
                $batchDetails[] = [
                    'batch_id' => $batch,
                    'batch_name' => $batchInfo->batch,
                    'mrp' => $batchInfo->mrp,
                    'expire_date' => $batchInfo->expire_date,
                ];
            }
        }
    
        return response()->json($batchDetails);
    }
    
    private function generateUniqueGrnNumber()
    {
        $year = Carbon::now()->format('y'); 
        $month = Carbon::now()->format('m');
    
        $lastId = GRNS::max('id') ?? 0;
        $nextId = str_pad($lastId + 1, 5, '0', STR_PAD_LEFT);
    
        $grnNumber = "GRN{$year}{$month}{$nextId}";
    
        return $grnNumber;
    }
    
    public function delete_grn($id,Request $request)
    {
        GRNS::find($id)->delete();
        return back()->with('success', 'GrRN Deleted');
    }
}