<?php

namespace App\Http\Controllers\Manufacturing;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class ProductionController extends Controller
{
    public function index(Request $request)
    {
        $query = DB::table('production');

        // Apply filters based on request parameters
        if ($request->has('search')) {
            $search = $request->input('search');
            $query->where(function ($q) use ($search) {
                $q->where('order_id', 'LIKE', "%$search%")
                  ->orWhere('date', 'LIKE', "%$search%")
                  ->orWhere('warehouse', 'LIKE', "%$search%")
                  ->orWhere('status', 'LIKE', "%$search%");
            });
        }


        if ($request->has('type')) {
            $type = $request->input('type');
            $query->where('type', $type);
        }

        $count=$query->count();
        
        $boms=$query->skip($request['noofrec']*($request['currentpage']-1))->take($request['noofrec']??50)
                ->orderBy('id','desc')
                ->get();

        return $response=[
            'success'=>true,
            'total'=>$count,
            'production'=>$boms,
            'message'=>'All Production Listed Successfully'
        ];
    }

    // Store a newly created requisition
    public function store(Request $request)
    {

        // Handle file upload if there's an attachment
        if ($request->hasFile('attachment')) {
            $file = $request->file('attachment');
            $filename = time() . '_' . $file->getClientOriginalName();
            $filePath = $file->storeAs('attachments', $filename, 'public');
            // $validatedData['attachment'] = $filePath;
        }
        else{
            $filename="";
        }
        
            $lastBOM = DB::table('boms')
                     ->select('id')
                     ->orderBy('id', 'desc')
                     ->count();

            $newId = $lastBOM + 1;
        $bom_id = 'BOM' . str_pad($newId, 3, '0', STR_PAD_LEFT);

    try {
        $productId = DB::table('boms')->insert([
            'id' => $bom_id,
            'name' => $request->product_name,
            'qty' => $request->qty,
            'unit_cost' => $request->unit_cost,
            'total_cost' => $request->total_cost,
            'status' => $request->status,
            
        ]);

        foreach ($request->rows as $row) {
            DB::table('bom_items')->insert([
                'bom_id' => $bom_id,
                'type' => 'Raw Material',
                'item_id' => $row['item_id'],
                'unit_price' => $row['price'],
                'req_qty' => $row['quantity'],
                'uom' => $row['unit'],
                'total_price' => $row['finalAmount'],
                'item_name' => $row['item_name'],
                
            ]);
        }

        foreach ($request->charges as $charge) {
            DB::table('bom_charges')->insert([
                'bom_id' => $bom_id,
                'charges_id' => $charge['charges_id'],
                'amount' => $charge['amount'],
                'charges_name' => $charge['charges_type'],
                'notes' => $charge['notes'],
                
            ]);
        }

        foreach ($request->routings as $routing) {
            DB::table('bom_operations')->insert([
                'bom_id' => $bom_id,
                'operation_id' => $routing['operation_id'],
                'operation_name' => $routing['operation_name'],
                'estimate_time' => $routing['estimate_time'],
                
            ]);
        }

        foreach ($request->scraps as $scrap) {
            DB::table('bom_items')->insert([
                'bom_id' => $bom_id,
                'type' => 'Scrap',
                'item_id' => $scrap['scrap_id'],
                'item_name' => $scrap['scrap_name'],
                'req_qty' => $scrap['quantity'],
                'remarks' => $scrap['notes'],
                
            ]);
        }

        return response()->json(['success' => true, 'message' => 'Bom created successfully'], 201);
    } catch (\Exception $e) {
        DB::rollBack();
        return response()->json(['success' => false, 'message' => 'Failed to create bom', 'error' => $e->getMessage()], 500);
    }
        
        
    }
    
    
    // Retrieve BOM details by BOM ID
    public function show(Request $request)
    {
        $production_id = $request->production_id;
        $production = DB::table('production')->where('production_id', $production_id)->first();
        $bom_id= $production->bom_id;

        if (!$production) {
            return response()->json(['message' => 'Production not found'], 404);
        }
        

        $bom_items = DB::table('bom_items')->where('bom_id', $bom_id)->where('type', 'Raw Material')->get();
        $bom_charges = DB::table('bom_charges')->where('bom_id', $bom_id)->get();
        $bom_scraps = DB::table('bom_items')->where('bom_id', $bom_id)->where('type', 'Scrap')->get();
        $bom_packaging_items = DB::table('bom_items')->where('bom_id', $bom_id)->where('type', 'Packaging Material')->get();
        $bom_operations = DB::table('bom_operations')->where('bom_id', $bom_id)->get();
        

        $items_details = DB::table('bom_items')
            ->join('inventory_items', 'bom_items.item_id', '=', 'inventory_items.item_id')
            ->where('bom_items.bom_id', $bom_id)
            ->where('bom_items.type', 'Raw Material')
            ->select('bom_items.*', 'inventory_items.item_name as item_name', 'inventory_items.quantity as avl_qty', 'inventory_items.description as item_description', 'inventory_items.unit_price')
            ->get();


        $productionDetails = [
            'production' => $production,
            'bom_items' => $bom_items,
            // 'items_details' => $items_details,
            'bom_packaging_items' => $bom_packaging_items,
            'bom_charges' => $bom_charges,
            'bom_operations' => $bom_operations,
            'bom_scraps' => $bom_scraps
        ];

        return response()->json($productionDetails, 200);
    }
    
     public function record_operation(Request $request)
    {
        // $request->validate([
        //     'operation_id' => 'required|string|max:255',
        //     'production_id' => 'required|string|max:255',
        //     'workstation' => 'required|string|max:255',
        //     'machinery' => 'required|string|max:255',
        //     'machine_datetime' => 'required|date',
        //     'notes' => 'nullable|string',
        //     'attachments.*' => 'nullable|file|mimes:jpeg,png,jpg,pdf,doc,docx|max:2048',
        // ]);

        $attachmentPaths = [];
        if ($request->hasFile('attachments')) {
            foreach ($request->file('attachments') as $file) {
                $path = $file->store('attachments', 'public');
                $attachmentPaths[] = $path;
            }
        }

        // Record operation
        DB::table('production_operations')->insert([
            'operation_id' => $request->input('operation_id'),
            'production_id' => $request->input('production_id'),
            'workstation' => $request->input('workstation'),
            'machinery' => $request->input('machinery'),
            'machine_datetime' => $request->input('machine_datetime'),
            'notes' => $request->input('notes'),
            'attachments' => json_encode($attachmentPaths),  // Store file paths as JSON
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return redirect()->back()->with('success', 'Operation recorded successfully.');
    }
    
     public function record_quantity(Request $request)
    {
        // $request->validate([
        //     'production_id' => 'required|string|max:255',
        //     'operation_id' => 'required|string|max:255',
        //     'available_qty' => 'required|string|max:255',
        //     'date' => 'required|date',
        //     'quantity' => 'required|numeric',
        //     'logistic_type' => 'required|in:Conveyor,Trolley,Vehicle',
        //     'notes' => 'nullable|string',
        //     'attachment' => 'nullable|file|mimes:jpeg,png,jpg,pdf,doc,docx|max:2048',
        // ]);

        $attachmentPath = null;
        if ($request->hasFile('attachment')) {
            $attachmentPath = $request->file('attachment')->store('attachments', 'public');
        }

        DB::table('production_quantity')->insert([
            'production_id' => $request->input('production_id'),
            'operation_id' => $request->input('operation_id'),
            'available_qty' => $request->input('available_qty'),
            'date' => $request->input('date'),
            'type' => $request->input('type'),
            'quantity' => $request->input('quantity'),
            'logistic_type' => $request->input('logistic_type'),
            'notes' => $request->input('notes'),
            'attachment' => $attachmentPath,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return redirect()->back()->with('success', 'Quantity recorded successfully.');
    }
    
      public function record_scrap(Request $request)
    {

        // Handle file upload
        $attachmentPath = null;
        if ($request->hasFile('attachment')) {
            $attachmentPath = $request->file('attachment')->store('attachments', 'public');
        }

        // Insert into production_scrap table
        DB::table('production_scrap')->insert([
            'production_id' => $request->input('production_id'),
            'date' => $request->input('date'),
            'type' => $request->input('type'),
            'action_type' => $request->input('action_type'),
            'warehouse' => $request->input('warehouse'),
            'scrap_qty' => $request->input('scrap_qty'),
            'notes' => $request->input('notes'),
            'attachment' => $attachmentPath,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return redirect()->back()->with('success', 'Scrap recorded successfully.');
    }
    
    
    public function record_finisged_goods(Request $request)
    {

        // $request->validate([
        //     'type' => 'required|in:Add,Move',
        //     'date' => 'required|date',
        //     'produced_qty' => 'required|numeric',
        //     'notes' => 'nullable|string',
        //     'attachment' => 'nullable|file|mimes:jpeg,png,jpg,pdf,doc,docx|max:2048',
        // ]);

        $attachmentPath = null;
        if ($request->hasFile('attachment')) {
            $attachmentPath = $request->file('attachment')->store('attachments', 'public');
        }

        DB::table('production_finished_goods')->insert([
            'production_id' => $request->input('production_id'),
            'action_type' => $request->input('action_type'),
            'date' => $request->input('date'),
            'produced_qty' => $request->input('produced_qty'),
            'notes' => $request->input('notes'),
            'attachment' => $attachmentPath,
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        return redirect()->back()->with('success', 'Finished goods recorded successfully.');
    }
    
    
}   
        