<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Factory;

class FactoryController extends Controller
{
    public function index()
    {
        $factories = Factory::latest()->paginate(10);
        return view('admin.factories.index', compact('factories'));
    }

    public function create()
    {
        return view('admin.factories.create');
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'location' => 'nullable|string',
            'contact_person' => 'nullable|string',
            'email' => 'nullable|email',
            'phone' => 'nullable|string',
            'compliance_doc' => 'nullable|file|mimes:pdf,doc,docx,jpg,jpeg,png|max:2048',
        ]);

        $data = $request->all();

        if ($request->hasFile('compliance_doc')) {
            $file = $request->file('compliance_doc');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('compliance_docs'), $filename);
            $data['compliance_doc'] = 'compliance_docs/' . $filename;
        }

        Factory::create($data);

        return redirect()->route('admin.factories.index')->with('success', 'Factory added successfully.');
    }

    public function edit(Factory $factory)
    {
        return view('admin.factories.edit', compact('factory'));
    }

    public function update(Request $request, Factory $factory)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'location' => 'nullable|string',
            'contact_person' => 'nullable|string',
            'email' => 'nullable|email',
            'phone' => 'nullable|string',
            'compliance_doc' => 'nullable|file|mimes:pdf,doc,docx,jpg,jpeg,png|max:2048',
        ]);

        $data = $request->all();

        if ($request->hasFile('compliance_doc')) {
            // Delete old file if exists
            if ($factory->compliance_doc && file_exists(public_path($factory->compliance_doc))) {
                unlink(public_path($factory->compliance_doc));
            }

            $file = $request->file('compliance_doc');
            $filename = time() . '_' . $file->getClientOriginalName();
            $file->move(public_path('compliance_docs'), $filename);
            $data['compliance_doc'] = 'compliance_docs/' . $filename;
        }

        $factory->update($data);

        return redirect()->route('admin.factories.index')->with('success', 'Factory updated successfully.');
    }

    public function destroy(Factory $factory)
    {
        // Delete file from public if exists
        if ($factory->compliance_doc && file_exists(public_path($factory->compliance_doc))) {
            unlink(public_path($factory->compliance_doc));
        }

        $factory->delete();
        return back()->with('success', 'Factory deleted.');
    }
}
