<?php

namespace App\Http\Controllers;

use App\Http\Requests\Company\StoreCompanyRequest;
use App\Http\Requests\Company\UpdateCompanyRequest;
use App\Http\Resources\CompanyResource;
use App\Http\Resources\UserResource;
use App\Models\Company;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class CompanyController extends Controller
{
    public function __construct()
    {
        $this->middleware(['auth:sanctum', 'role:company_admin,staff'])->only(['show', 'edit']);
        $this->middleware(['auth:sanctum', 'role:company_admin'])->only(['update']);
    }

    public function create(StoreCompanyRequest $request)
    {
        DB::beginTransaction();

        try {
            $company = Company::create([
                'company_name' => $request->company_name,
                'company_email' => $request->company_email,
                'company_phone' => $request->company_phone,
                'logo' => $request->logo,
                'address' => $request->address,
            ]);

            $user = User::create([
                'user_name' => $request->user_name,
                'user_email' => $request->user_email,
                'user_phone' => $request->user_phone,
                'password' => bcrypt($request->password),
                'company_id' => $company->id,
            ]);

            DB::commit();

            return $this->success([
                'message' => 'User and company created successfully.',
                'code' => 201,
                'data' => [
                    'company' => new CompanyResource($company),
                    'user' => new UserResource($user),
                    'token' => $user->createToken('ChristJesus '.$user->user_email)->plainTextToken,
                ],
            ]);
        } catch (\Exception $e) {
            DB::rollBack();

            return $this->error([
                'message' => 'Error creating user and company.',
                'code' => 422,
                'data' => $e->getMessage(),
            ]);
        }
    }

    public function show($id)
    {
        $company = Company::with(['terminals'])->findOrFail($id);

        return $this->success([
            'data' => new CompanyResource($company),
        ]);
    }

    public function edit($id)
    {
        $company = Company::findOrFail($id);

        return $this->success([
            'data' => new CompanyResource($company),
        ]);
    }

    public function update(UpdateCompanyRequest $request, $id)
    {
        $validatedData = $request->validated();

        $company = Company::findOrFail($id);
        $company->update($validatedData);

        return $this->success([
            'message' => 'Company updated successfully.',
            'data' => new CompanyResource($company),
        ]);
    }
}
