<?php

namespace App\Http\Controllers;

use App\Models\CompanyModel;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Log;

class CompanyController extends Controller
{
    protected $rules = [
        'name' => 'required|max:255',
        'email' => 'email',
        'contact_number' => 'regex:/^[0-9]{10,15}$/',
        'address' => 'max:255',
    ];

    public function __construct()
    {
        $this->middleware('auth'); // Add auth middleware if needed
    }

    public function index(Request $request)
    {
        $search = $request->input('search');

        $companies = CompanyModel::orderBy('id', 'desc')->get();

        $users = User::where('user_flg', 'A')->get();

        return view('company.index', compact('companies', 'users'));
    }

    public function create()
    {
        $users = User::where('user_flg', 'A')->get();
        return view('company.add', compact('users'));
    }

    public function store(Request $request)
    {
        $request->validate($this->rules);

        DB::beginTransaction();
        try {
            if ($request->hasFile('logo')) {
                $logo_path = storeFile($request->file('logo'), 'landingpage');
            } else {
                $logo_path = null;
            }

            $company = CompanyModel::create([
                'prefix' => $request->prefix,
                'name' => $request->name,
                'phone' => $request->contact_number,
                'email' => $request->email,
                'address' => $request->address,
                'logo' => $logo_path,
                'application_name' => $request->application_name,
            ]);

            DB::table('company_user')->insert([
                'user_id' => $request->user_id,
                'company_id' => $company->id,
            ]);

            DB::commit();
            return redirect()->route('company-index')
                ->with('success', 'Company added successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('While creating company' . $e);
            return back()->with('error', 'Something went wrong! Please try again');
        }
    }

    public function edit($id)
    {
        $company = CompanyModel::findOrFail($id);
        $users = User::where('user_flg', 'A')->get();

        $companyUser = DB::table('company_user')->where('company_id', $company->id)->first();

        $user_id = $companyUser ? $companyUser->user_id : null;

        return view('company.edit', compact('company', 'users', 'user_id'));
    }

    public function update(Request $request)
    {
        $request->validate($this->rules);

        DB::beginTransaction();
        try {
            $company = CompanyModel::findOrFail($request->company_id);

            if ($request->hasFile('logo')) {
                $logo_path = storeFile($request->file('logo'), 'landingpage');
            } else {
                $logo_path = $company->logo;
            }

            $company->update([
                'prefix' => $request->prefix,
                'name' => $request->name,
                'phone' => $request->contact_number,
                'email' => $request->email,
                'address' => $request->address,
                'logo' => $logo_path,
                'application_name' => $request->application_name,
            ]);

            $exists = DB::table('company_user')
                ->where('company_id', $company->id)
                ->where('user_id', $request->user_id)
                ->exists();

            if ($exists) {
                DB::table('company_user')
                    ->where('company_id', $company->id)
                    ->where('user_id', $request->user_id)
                    ->update([
                        'company_id' => $company->id,
                        'user_id' => $request->user_id
                    ]);
            } else {
                // Delete existing relations and create new one
                DB::table('company_user')->where('company_id', $company->id)->delete();
                DB::table('company_user')->insert([
                    'company_id' => $company->id,
                    'user_id' => $request->user_id
                ]);
            }

            DB::commit();
            return redirect()->route('company-index')
                ->with('success', 'Company updated successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('While updating company' . $e);
            return back()->with('error', 'Something went wrong! Please try again');
        }
    }

    public function delete($id)
    {
        $company = CompanyModel::findOrFail($id);

        if ($company->logo) {
            Storage::delete($company->logo);
        }

        $company->delete();

        return redirect()->route('company-index')
            ->with('success', 'Company deleted successfully!');
    }

    // protected function storeFile($file, $directory)
    // {
    //     return $file->store($directory, 'public');
    // }
}