<?php

namespace App\Http\Controllers;

use App\Models\Sparepart;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Yajra\DataTables\Facades\DataTables;

class SparepartController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        if ($request->ajax()) {
            $spareparts = Sparepart::latest()->select(['id', 'name', 'code', 'image', 'stock', 'location', 'description']);
            return DataTables::of($spareparts)
                ->addIndexColumn()
                ->addColumn('action', function ($row) {
                    $btn = '<div class="flex justify-center gap-2">';
                    $btn .= '<a href="javascript:void(0)" data-id="'.$row->id.'" style="background-color: #3b82f6; color: white; border-radius: 8px;" class="edit inline-block px-3 py-1 bg-blue-500 text-white rounded-lg shadow-sm hover:bg-blue-600 transition duration-150 ease-in-out">Edit</a>';
                    $btn .= '<a href="javascript:void(0)" data-id="'.$row->id.'" style="background-color: #ef4444; color: white; border-radius: 8px;" class="delete inline-block px-3 py-1 bg-red-500 text-white rounded-lg shadow-sm hover:bg-red-600 transition duration-150 ease-in-out">Delete</a>';
                    $btn .= '</div>';
                    return $btn;
                })
                ->addColumn('image_display', function($row){
                    if ($row->image) {
                        $url = asset('storage/'.$row->image);
                        return '<div class="image-trigger cursor-pointer flex justify-center" data-src="'.$url.'">
                                    <img src="'.$url.'" alt="Sparepart" style="width: 50px; height: 50px; object-fit: cover;" class="rounded border border-gray-200 hover:opacity-75 transition shadow-sm">
                                </div>';
                    }
                    return '<span class="text-gray-400 text-xs text-center block">No Image</span>';
                })
                ->addColumn('qr_code', function($row){
                     return '<img src="https://api.qrserver.com/v1/create-qr-code/?size=50x50&data='.$row->code.'" alt="QR">';
                })
                ->rawColumns(['action', 'image_display', 'qr_code'])
                ->make(true);
        }
        return view('spareparts.index');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'stock' => 'required|integer|min:0',
            'code' => 'nullable|string|unique:spareparts,code|max:50',
            'location' => 'nullable|string|max:100',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ]);

        $data = $request->all();
        if (empty($data['code'])) {
            $data['code'] = 'SP-' . strtoupper(Str::random(8));
        }

        // Handle image upload
        if ($request->hasFile('image')) {
            $image = $request->file('image');
            if ($image->isValid()) {
                $extension = $image->getClientOriginalExtension();
                $imageName = time() . '_' . Str::random(10) . '.' . $extension;
                // Use Storage::put with file_get_contents to avoid fopen/getRealPath issues
                \Storage::disk('public')->put('spareparts/' . $imageName, file_get_contents($image));
                $data['image'] = 'spareparts/' . $imageName;
            }
        }

        Sparepart::create($data);

        return response()->json(['success' => 'Sparepart created successfully.']);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit($id)
    {
        $sparepart = Sparepart::find($id);
        return response()->json($sparepart);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        $sparepart = Sparepart::find($id);

        $validations = [
            'name' => 'required|string|max:255',
            'stock' => 'required|integer|min:0',
            'location' => 'nullable|string|max:100',
            'description' => 'nullable|string',
            'image' => 'nullable|image|mimes:jpeg,png,jpg,gif|max:2048',
        ];

        if ($request->filled('code') && $request->code != $sparepart->code) {
             $validations['code'] = 'nullable|string|unique:spareparts,code,' . $id . '|max:50';
        }

        $request->validate($validations);

        $data = $request->all();

        // Explicitly remove 'code' from request to prevent updates
        unset($data['code']);
        if ($request->has('code')) {
             $request->request->remove('code');
        }

        // Handle image upload
        if ($request->hasFile('image')) {
            $image = $request->file('image');

            if ($image->isValid()) {
                // Delete old image if exists
                if (!empty($sparepart->image) && \Storage::disk('public')->exists($sparepart->image)) {
                    \Storage::disk('public')->delete($sparepart->image);
                }

                $extension = $image->getClientOriginalExtension();
                $imageName = time() . '_' . Str::random(10) . '.' . $extension;
                // Use Storage::put with file_get_contents to avoid fopen/getRealPath issues
                \Storage::disk('public')->put('spareparts/' . $imageName, file_get_contents($image));
                $data['image'] = 'spareparts/' . $imageName;
            }
        }

        $sparepart->update($data);

        return response()->json(['success' => 'Sparepart updated successfully.']);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy($id)
    {
        $sparepart = Sparepart::find($id);

        // Delete image if exists
        if ($sparepart->image && \Storage::disk('public')->exists($sparepart->image)) {
            \Storage::disk('public')->delete($sparepart->image);
        }

        $sparepart->delete();
        return response()->json(['success' => 'Sparepart deleted successfully.']);
    }
}
