<?php

namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Item;
use App\Models\StockTransaction;
use App\Models\User;
use App\Models\Activity;
use validator;
use Auth;
use Maatwebsite\Excel\Facades\Excel;
use App\Imports\ItemImport;
use App\Imports\ItemExport;

use App\Service\ActivityService;
use App\Service\StockEntryService;
use App\Service\Tms\VehicleService;
use App\Service\Tms\TrailerService;
use App\Service\Tms\RimService;
use App\Service\Tms\TyreService;
use App\Service\Tms\BatteryService;
use App\Service\StaticMaster;
use Log;

class ItemController extends Controller
{

    public function itemCreateUpdate(Request $request){
        // Validate Item
        $validator=validator($request->all(),[

            'name'=>'required|string',
            'type'=>'required',
            // 'unit'=>'required'
        ]);

        if ($validator->fails()) { 

            return [
                'success' => false, 
                'message' => $validator->errors()->first()
            ];

        } else {

        // defining data variables

            $data=[

                'name','category_id','category_name','sub_category_name',

                'sub_category_id','description','sku',

                'price','unit','tax_rate','opening_stock','type','purchase_price','tag_ids',

                'image_url','sale_acc_id','purchase_acc_id','custom_fields','as_on_date','hsn_code',

                'preferred_vendor','sale_description','purchase_description','exemption_reason',

                'tax_preference','is_sale','is_purchase','attachments',
                'company_sku','part_id','user_id',

                'related_product_ids',
                'brand_id','brand_name'

            ];

            // Assign valiables to objects
            $obj=[];

            foreach ($data as $key => $value) {
                if(isset($request[$value]) && $request[$value]!=null && $request[$value]!=''){
                    $obj[$value]=$request[$value];
                }
                if($request[$value]==''){
                    $obj[$value]=null;
                }
            }
            if($request['id']>0){

                // Updating an existing  item
                try {

                    $item=Item::findOrFail($request['id']);

                    $item->update($obj);

                    //Creating New Product Variant
                    if(isset($request['new_items']) && $request['new_items']!=null && $request['new_items']!=''){

                        if(count($request['new_items']) > 0){

                            // Step 1: Create all items first
                            foreach ($request['new_items'] as $prod) {

                                $obj['company_sku'] = $prod['company_sku'];
                                $obj['sku'] = $prod['sku'];
                                $obj['brand_name'] = $prod['brand_name'];
                                $obj['brand_id'] = $prod['brand_id'];

                                $newItem = Item::create($obj);
                                $createdItems[] = $newItem; // collect full model
                            }

                            // Step 2: Assign related_product_ids to each
                            $allIds = collect($createdItems)->pluck('id')->toArray();

                            $allIds[] = $item['id']; // Add current item's ID

                            foreach ($createdItems as $item1) {
                                // Exclude current item's own ID
                                $relatedIds = array_values(array_diff($allIds, [$item1->id]));

                                $item1->related_product_ids = json_encode($relatedIds);
                                $item1->update(); // Or $item->update();
                            }

                            $item->related_product_ids = json_encode(array_values(array_diff($allIds, [$item->id])));
                            $item->update();
                        }
                    }


                    // Creating Activities
                    // $activity=new ActivityService;

                    // $activity->activityCreateUpdate('Item',$item['id'],'Updated');

                } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {
                    // Return error message in JSON if ID not found
                    return response()->json(['message' => 'Invalid Id found'], 404);
                }

            }else{

                // Checking for Duplicate SKU
                if($obj['sku']!=null && $obj['sku']!=''){
                    $check=Item::where('sku',$obj['sku'])
                        ->where('is_disabled',0)
                        ->where('type','Product')
                        ->first();

                    if($check!=null){

                        $response=[

                            'item'=>$check,
                            'success'=>false,
                            'message'=>'Duplicate SKU '.$check['sku'] .' Found!'
                        ];
                        return response()->json($response);

                    }
                }

                // Creating New Item
                $item=Item::create($obj);

                // Creating Activities
                // $activity=new ActivityService;
                // $activity->activityCreateUpdate('Item',$item['id'],'Created');

            }

            $response=[
                'item'=>$item,
                'success'=>true,
                'message'=>'Item Created Successfully'
            ];

            return response()->json($response);
        }
    }


    public function itemList(Request $request){

        $user=Auth::user();

        // $validator=validator($request->all(),[
        //     'warehouse_id'=>'required|integer'
        // ]);

        // if ($validator->fails()) { 

        //     return [
        //         'success' => false, 

        //         'message' => $validator->errors()->first(),

        //         'items_details' => null

        //     ];

        // } else {

        if($user!=null){

            $item=Item::where('organisation_id',$user['active_organisation'])
                ->with('category','sub_category')
                ->where('is_disabled',0);

            //user id wise
            if($request['user_id']!=0 && $request['user_id']!=""){

                $item=$item->where('user_id',$request['user_id']);
            }
            // Filters
            if(isset($request['active'])){

                $item=$item->where('active',$request['active']);

            }

            if($request['part_id']!='' && $request['part_id']!=null){

                // Goods , Services , Raw ,Packaging
                $item=$item->where('part_id',$request['part_id']);

            }
            if($request['type']!='' && $request['type']!=null){

                // Goods , Services , Raw ,Packaging
                $item=$item->where('type',$request['type']);

            }

            if($request['types']!='' && $request['types']!=null){

                // Goods , Services , Raw ,Packaging
                $item=$item->whereIn('type',$request['types']);
            }

            if(isset($request['manufacturing_store']) && $request['manufacturing_store']==1){

                // Goods , Services , Raw ,Packaging
                $item=$item->where('manufacturing_store','>',0);
            }

            if($request['search']!=null && $request['search']!=''){

                $item = $item->where(function ($query) use ($request) {

                    $query->where('name', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('sku', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('brand_name', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('description', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhere('part_id', 'LIKE', '%' . $request['search'] . '%')

                    ->orWhereHas('category', function ($query) use ($request) {
                        $query->where('name', 'LIKE', '%' . $request['search'] . '%');
                    })

                    ->orWhereHas('sub_category', function ($query) use ($request) {
                        $query->where('name', 'LIKE', '%' . $request['search'] . '%');
                    });

                });
            }

            // get Alphabetically data by name

            if ($request->has('name') && $request->name === '1') {

                $item = $item->orderBy('name');

            }
            // get price data by ascending  or descending

            if ($request->has('price')) {

                if ($request->price === '1') {

                    $item = $item->orderBy('price');

                } elseif ($request->price === '0') {

                    $item = $item->orderByDesc('price');

                }

            }

                // get purchase_price data by ascending  or descending

            if ($request->has('purchase_price')) {

                if ($request->purchase_price === '1') {

                    $item = $item->orderBy('purchase_price');

                } elseif ($request->purchase_price === '0') {

                    $item = $item->orderByDesc('purchase_price');

                }

            }

            //In store or not
            if ($request->in_store == '1' && isset($request->in_store)) {
                $item = $item->where('in_store', 1);
            } 

            //In Tms store or not
            if ($request->in_tms == '1' && isset($request->in_tms)) {
                $item = $item->where('in_tms', 1);
            } 
            if ($request->tms_store ==1) {
                $item = $item->where('tms_store','>',0);
            } 

            // Count all the items

            $item_count=$item->count();

            // Pagination

            $item=$item->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)

                ->orderBy('id','desc')

                ->get();

            $response=[

                'success'=>true,

                'message'=>'Items fetched Successfully',

                'total_items'=>$item_count,

                'item'=>$item

            ];

        } else {

            $response=[

                'success'=>false,

                'message'=>'Your Are not Authenticated',

                'total_items'=>null,

                'item'=>null

            ];
        }

        return response()->json($response);

    }



    public function itemDetails(Request $request){

        $user=Auth::user();

        if($user!=null){

            // Validate Item

            $validator=validator($request->all(),[
                'item_id'=>'required|integer',
                'fy'=>'required'
                // 'warehouse_id'=>'required'
            ]);

            if ($validator->fails()) { 

                return [
                    'success' => false, 
                    'message' => $validator->errors()->first(),
                    'items_details' => null
                ];

            } else {

                // Fetch item details
                $item_details =  Item::where('id',$request->input('item_id'))
                    ->first();

                $response = [
                    'success' => true,
                    'message' => 'Item detail fetched Successfully',
                    'item_details' => $item_details
                ];

            } 

        } else {

            $response=[
                'success'=>false,
                'message'=>'Your Are not Authenticated',
                'items_details'=>null
            ];

        }

        return response()->json($response);
    }



    // public function itemActivity(Request $request){
    //     // Validate Item

    //     $validator=validator($request->all(),[

    //         'item_id'=>'required|integer',
    //         'fy'=>'required'

    //     ]);

    //     if ($validator->fails()) { 

    //         return [
    //             'success' => false, 
    //             'message' => $validator->errors()->first(),
    //             'items_details' => null
    //         ];

    //     } else {

    //         $activity=Activity::where('module','Item')
    //             ->where('module_id',$request['item_id'])
    //             ->with('entryby');

    //         if ($request['custom_date']!='' && isset($request['custom_date'])) {

    //             $customDate = $request->custom_date;

    //             $activity = $activity->whereDate('date', $customDate);

    //         }
    
    //             if ($request['from_date']!='' && isset($request['to_date'])) {
    
    //                 $fromDate = $request->from_date;
    
    //                 $toDate = $request->to_date;
    
    //                 // 'fromDate' and 'toDate'
    
    //                 $activity = $activity->whereBetween('date', [$fromDate, $toDate]);
    
    //             }
                
    //             $activity=$activity->orderBy('date','desc')
    
    //                 ->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??100)
    
    //                 ->get();
    
    //                 $response = [
    //                     'success' => true,
    //                     'message' => 'Item Activity fetched Successfully',
    //                     'activity' => $activity,
    //                 ];
    
    //             return response()->json($response);
    //     }
    // }

    // Import Excel To database
    public function import(Request $request){
        // Validate Item

        $validator=validator($request->all(),[

            'file' => 'required|file'

        ]);

        if ($validator->fails()) { 

            return [

                'success' => false, 

                'message' => $validator->errors()->first()

            ];

        } else {

            $file = $request->file('file');
            Excel::import(new ItemImport, $file);
            // Creating Activities

            $activity=new ActivityService;

            $activity->activityCreateUpdate('Item',0,'Imported');
            // return redirect()->back()->with('success', 'Item imported successfully!');

            $response=[

                'success'=>true,

                'message'=>'Item Excel Imported Successfully'

            ];
            return response()->json($response);

        }

    }

    // Export data to excel  File
    public function export(){

        // Creating Activities

        $activity=new ActivityService;

        $activity->activityCreateUpdate('Item',0,'Exported');



        return Excel::download(new ItemExport, 'products.xlsx');

    }

    // item custome fields

    public  function customItemFields(){

       $fields=CustomField::where('type','item')->get();

       return response()->json([

           'fields'=>$fields

       ]);

    }



    public function  addCustomField(Request $request){

          $this->validate($request,[

              'field_name'=>'required',

              'label'=>'required',

              'field_type'=>'required',

            //   'required_status'=>'required',

          ]);

         $customField= new CustomField();

         $customField->field_name='items';

         $customField->field_name=$request->field_name;

         $customField->field_type=$request->field_type;

         $customField->required_status=$request->required_status??0;

         $customField->type='item';

         $customField->save();

         return response()->json(['msg'=>'Field added Successfully']);

     }

     

    
    
     public function status(Request $request){

         // Validate Item

         $validator=validator($request->all(),[

            'item_id'=>'required|integer',

            'active'=>'required|integer'

        ]);



        if ($validator->fails()) { 

            return [

                'success' => false, 

                'message' => $validator->errors()->first(),

            ];



        } else {



            try{

                $item =  Item::where('id',$request->input('item_id'))->first();

                $item['active']=$request['active'];

                $item->update();



                $response=[

                    'success'=>true,

                    'message'=>'Status Updated successfully.',

                    'item'=>$item

                ];

            } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {

                // Return error message in JSON if ID not found

                return response()->json(['message' => 'Invalid Id found'], 404);

            }



            return response()->json($response);



        }

    }



    public function delete(Request $request){

        $user=Auth::user();

        // Validate Item

        $validator=validator($request->all(),[

           'item_id'=>'required|integer'

       ]);



       if ($validator->fails()) { 

           return [

               'success' => false, 

               'message' => $validator->errors()->first(),

           ];



       } else {



           try{

               $item =  Item::where('id',$request->input('item_id'))

                    ->where('organisation_id',$user['active_organisation'])

                    ->first();

               $item['is_disabled']=1;

               $item->update();



               $response=[

                   'success'=>true,

                   'message'=>'Item Deleted successfully.'

                //    'item'=>$item

               ];

           } catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e) {

               // Return error message in JSON if ID not found

               return response()->json(['message' => 'Invalid Id found'], 404);

           }



           return response()->json($response);



       }

    }

    public function relatedItemsList(Request $request)
    {
        $validator = validator($request->all(), [
            'item_id' => 'required'
        ]);

        if ($validator->fails()) {
            return [
                'success' => false,
                'message' => $validator->errors()->first()
            ];
        }

        $item = Item::find($request['item_id']);

        // Decode the JSON string to array
        $related_ids = json_decode($item->related_product_ids, true); // <- fix here

        // Validate that it's an array
        if (!is_array($related_ids)) {
            $related_ids = [];
        }

        $related_items = Item::whereIn('id', $related_ids)
            ->with(['category', 'sub_category']);

        if (!empty($request['search'])) {
            $related_items = $related_items->where(function ($query) use ($request) {
                $query->where('name', 'LIKE', '%' . $request['search'] . '%')
                    ->orWhere('sku', 'LIKE', '%' . $request['search'] . '%')
                    ->orWhere('brand_name', 'LIKE', '%' . $request['search'] . '%')
                    ->orWhere('description', 'LIKE', '%' . $request['search'] . '%')
                    ->orWhere('part_id', 'LIKE', '%' . $request['search'] . '%')
                    ->orWhereHas('category', function ($query) use ($request) {
                        $query->where('name', 'LIKE', '%' . $request['search'] . '%');
                    })
                    ->orWhereHas('sub_category', function ($query) use ($request) {
                        $query->where('name', 'LIKE', '%' . $request['search'] . '%');
                    });
            });
        }

        $count = $related_items->count();

        return response()->json([
            'success' => true,
            'message' => 'Related Items fetched successfully.',
            'total' => $count,
            'items' => $related_items->get() // <- don't forget ->get() here
        ]);
    }



}

