<?php

namespace App\Http\Controllers;

use App\Models\BranchModel;
use App\Models\CentralizedUsers;
use App\Models\CompanyModel;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class SettingsController extends Controller
{
    public function privacypolicy()
    {
       return view('policy.privacy');
    }	
    public function show()
    {
        return view('settings.settings');
    }
    public function save(Request $request)
    {
        try {
            DB::beginTransaction();
            $host = request()->getHost();
            $subdomain = $host;

            $company = CompanyModel::create([
                'name' => $request->company,
                'address' => '1234 Elm Street Apt. 56B',
                'phone' => $request->phone,
                'email' => $request->email,
                'prefix' => 'INV',
                'application_name' => 'Billing'
            ]);

            $branch = BranchModel::create([
                'company_id' => $company->id,
                'name' => $request->branch,
                'address' => '1234 Elm Street Apt. 60B',
                'phone' => $request->phone,
                'company_name' => $request->company,
                'email' => $request->email,
                'prefix' => 'INV',
                'whatsapp_config' => 'I',
            ]);

            $user = User::create([
                'branch_id' => $branch->id,
                'name' => $request->super_admin_name,
                'email' => $request->email,
                'phone' => $request->phone,
                'password' => Hash::make($request->password),
                'active_status' => 'A',
                'user_flg' => 'SU',
            ]);
            $com_user = DB::table('company_user')->insert([
                'user_id' => $user->id,
                'company_id' => $company->id
            ]);
            $branch_user = DB::table('branch_user')->insert([
                'user_id' => $user->id,
                'branch_id' => $branch->id,
            ]);
            
            CentralizedUsers::create([
                'name' => $request->super_admin_name,
                'email' => $request->email,
                'phone' => $request->phone,
                'domain_name' => $subdomain,
            ]);

            //    centralizedUsers($request->super_admin_name, $request->email, $request->phone);
            DB::commit();

            return back()->with('success', 'Super Admin saved successfully!');
        } catch (\Exception $e) {
            DB::rollBack();
            return redirect()->back()->with('error', 'An error occurred: ' . $e->getMessage());
        }
    }


}
