<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\company;
use Illuminate\Support\Facades\Log;

class CompanyController extends Controller
{
    public function index()
    {
        $companies = Company::select('id', 'name', 'shortCode', 'wearHouse')->get();
        return response()->json($companies);
    }

    public function create()
    {
        return view('company.create');
    }
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'shortCode' => 'required|string|max:10',
            'wearHouse' => 'required|boolean', // Change this to boolean
        ]);

        // Ensure correct data format
        Company::create([
            'name' => $request->name,
            'shortCode' => $request->shortCode,
            'wearHouse' => $request->wearHouse ? 1 : 0, // Convert boolean to integer
        ]);

        return response()->json(['message' => 'Company created successfully'], 201);
    }

    public function edit(company $company)
    {
        return view('company.edit', compact('company'));
    }
    public function update(Request $request, $id)
    {
        // Find the specific company by ID
        $company = Company::find($id);
        if (!$company) {
            return response()->json(['message' => 'Company not found'], 404);
        }

        $request->validate([
            'name' => 'required',
            'shortCode' => 'required',
            'wearHouse' => 'required|boolean',
        ]);

        // Update the company record
        $company->update($request->only(['name', 'shortCode', 'wearHouse']));

        return response()->json(['message' => 'Company updated successfully!']);
    }



    public function destroy(company $company)
    {
        $company->delete();
        return redirect()->route('company.index');
    }
}
