<?php

namespace App\Http\Controllers\SuperAdmin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\RawMaterial;
use App\Models\RawMaterialFile;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Storage;

class SuperAdminRawMaterialController extends Controller
{
    public function index()
    {
        return view('superadmin.master.rawmaterials');
    }

    public function list()
    {
        $materials = RawMaterial::with(['files:id,raw_material_id,file_path,file_name'])
            ->select('id', 'rm_grade', 'iso_specification', 'density', 'raw_material_type')
            ->get();
    
        return response()->json(['data' => $materials]);
    }

    public function store_old(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'density' => 'required',
        ]);

        RawMaterial::create([
            'name' => $request->name,
            'iso_specification' => $request->iso_specification,
            'density' => $request->density,
            'mechanical_properties' => $request->mechanical_properties,
            'chemical_properties' => $request->chemical_properties,
        ]);

        return response()->json(['success' => true, 'message' => 'Raw Material added']);
    }
    
    public function store_new(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'rm_grade' => 'required|string|max:255|unique:raw_materials,rm_grade',
            'iso_specification' => 'nullable|string|max:255',
            'density' => 'required|numeric',
            'raw_material_type' => 'nullable|string|max:255',
            'material_file' => 'nullable|mimes:jpeg,png,jpg,gif,webp,pdf,doc,docx,xls,xlsx|max:5120'
        ], [
            'rm_grade.unique' => 'The raw material is already taken.',
        ]);


        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $validator->errors()
            ], 422);
        }

        $filePath = null;
        if ($request->hasFile('material_file')) {
            $filePath = $request->file('material_file')->store('materials', 'public');
        }

        RawMaterial::create([
            'rm_grade' => $request->rm_grade,
            'iso_specification' => $request->iso_specification,
            'density' => $request->density,
            'raw_material_type' => $request->raw_material_type,
            'material_file' => $filePath,
        ]);

        return response()->json(['success' => true, 'message' => 'Raw Material added']);
    }
    
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'rm_grade' => 'required|string|max:255|unique:raw_materials,rm_grade',
            'iso_specification' => 'nullable|string|max:255',
            'density' => 'required|numeric',
            'raw_material_type' => 'nullable|string|max:255',
            'material_file.*' => 'nullable|mimes:jpeg,png,jpg,gif,webp,pdf,doc,docx,xls,xlsx|max:5120'
        ], [
            'rm_grade.unique' => 'The raw material is already taken.',
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $validator->errors()
            ], 422);
        }
        
        //dd($request->file('material_file'));
    
        $material = RawMaterial::create([
            'rm_grade' => $request->rm_grade,
            'iso_specification' => $request->iso_specification,
            'density' => $request->density,
            'raw_material_type' => $request->raw_material_type,
        ]);
    
        if ($request->hasFile('material_file')) {
            foreach ($request->file('material_file') as $file) {
                $path = $file->store('materials', 'public');
                $material->files()->create([
                    'file_path' => $path,
                    'file_name' => $file->getClientOriginalName(),
                ]);
            }
        }
    
        return response()->json(['success' => true, 'message' => 'Raw Material added']);
    }

    public function show(RawMaterial $rawmaterial)
    {
        $rawmaterial->load('files'); // eager load related files
    
        return response()->json($rawmaterial);
    }

    public function update_old(Request $request, RawMaterial $rawmaterial)
    {
        $request->validate([
            'name' => 'required',
            'density' => 'required',
        ]);

        $rawmaterial->update([
            'name' => $request->name,
            'iso_specification' => $request->iso_specification,
            'density' => $request->density,
            'mechanical_properties' => $request->mechanical_properties,
            'chemical_properties' => $request->chemical_properties,
        ]);

        return response()->json(['success' => true, 'message' => 'Raw Material updated']);
    }
    
    public function update_singlefile(Request $request, RawMaterial $rawmaterial)
    {
        $validator = Validator::make($request->all(), [
            'rm_grade' => 'required|string|max:255',
            'iso_specification' => 'nullable|string|max:255',
            'density' => 'required|numeric',
            'raw_material_type' => 'nullable|string|max:255',
            'material_file' => 'nullable|mimes:jpeg,png,jpg,gif,webp,pdf,doc,docx,xls,xlsx|max:5120'
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $validator->errors()
            ], 422);
        }

        $filePath = $rawmaterial->material_file;

        if ($request->hasFile('material_file')) {
            if ($filePath && Storage::disk('public')->exists($filePath)) {
                Storage::disk('public')->delete($filePath);
            }
            $filePath = $request->file('material_file')->store('materials', 'public');
        }

        $rawmaterial->update([
            'rm_grade' => $request->rm_grade,
            'iso_specification' => $request->iso_specification,
            'density' => $request->density,
            'raw_material_type' => $request->raw_material_type,
            'material_file' => $filePath,
        ]);

        return response()->json(['success' => true, 'message' => 'Raw Material updated']);
    }
    
    public function update(Request $request, RawMaterial $rawmaterial)
    {
        $validator = Validator::make($request->all(), [
            'rm_grade' => 'required|string|max:255',
            'iso_specification' => 'nullable|string|max:255',
            'density' => 'required|numeric',
            'raw_material_type' => 'nullable|string|max:255',
            'material_file.*' => 'nullable|file|mimes:jpeg,png,jpg,gif,webp,pdf,doc,docx,xls,xlsx|max:5120'
        ]);
    
        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => 'Validation failed.',
                'errors' => $validator->errors()
            ], 422);
        }
    
        // Update raw material fields
        $rawmaterial->update([
            'rm_grade' => $request->rm_grade,
            'iso_specification' => $request->iso_specification,
            'density' => $request->density,
            'raw_material_type' => $request->raw_material_type,
        ]);
    
        // Handle new file uploads
        if ($request->hasFile('material_file')) {
            foreach ($request->file('material_file') as $file) {
                $path = $file->store('rawmaterials', 'public');
    
                $rawmaterial->files()->create([
                    'file_name' => $file->getClientOriginalName(),
                    'file_path' => $path,
                ]);
            }
        }
    
        return response()->json(['success' => true, 'message' => 'Raw Material updated successfully.']);
    }

    public function delete_old(RawMaterial $rawmaterial)
    {
        $rawmaterial->delete();
        return response()->json(['success' => true, 'message' => 'Raw Material deleted']);
    }
    
    public function delete_single(RawMaterial $rawmaterial)
    {
        if ($rawmaterial->material_file && Storage::disk('public')->exists($rawmaterial->material_file)) {
            Storage::disk('public')->delete($rawmaterial->material_file);
        }

        $rawmaterial->delete();

        return response()->json(['success' => true, 'message' => 'Raw Material deleted']);
    }
    
    public function deleteFile_single($id)
    {
        $material = RawMaterial::findOrFail($id);
    
        if ($material->material_file && Storage::disk('public')->exists($material->material_file)) {
            Storage::disk('public')->delete($material->material_file);
            $material->material_file = null;
            $material->save();
        }
    
        return response()->json(['success' => true, 'message' => 'File deleted successfully.']);
    }
    
    public function delete(RawMaterial $rawmaterial)
    {
        // Delete all associated files from storage and DB
        foreach ($rawmaterial->files as $file) {
            if ($file->file_path && Storage::disk('public')->exists($file->file_path)) {
                Storage::disk('public')->delete($file->file_path);
            }
            $file->delete();
        }
    
        // Delete the raw material itself
        $rawmaterial->delete();
    
        return response()->json(['success' => true, 'message' => 'Raw Material and associated files deleted successfully.']);
    }
    
    public function deleteFile($id)
    {
        $file = RawMaterialFile::findOrFail($id);
    
        if ($file->file_path && Storage::disk('public')->exists($file->file_path)) {
            Storage::disk('public')->delete($file->file_path);
        }
    
        $file->delete();
    
        return response()->json(['success' => true, 'message' => 'File deleted successfully.']);
    }
}
