<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Company;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

class CompanyController extends Controller
{
    public function index()
    {
        if (auth()->user()->role_id == 1) {
            // Superadmin created the company, so their ID is in superadmin_id
            $companies = Company::where('superadmin_id', auth()->id())->get();
        } else {
            // Company Admin's profile is found where user_id = their own user id
            $companies = Company::where('user_id', auth()->id())->get();
        }
        return view('admin.company.index', compact('companies'));
    }

    public function create()
    {
        if (auth()->user()->role_id != 1) {
            abort(403, 'Unauthorized');
        }
        return view('admin.company.create');
    }

    public function store(Request $request)
    {
        if (auth()->user()->role_id != 1) {
            abort(403, 'Unauthorized');
        }

        $validated = $request->validate([
            'company_name'    => 'required|string|max:255',
            'company_address' => 'required|string|max:255',
            'email'           => 'nullable|email|max:255|unique:users,email',
        ]);

        // Always use default password 123456
        $defaultPassword = '123456';

        // Use the exact company name as the username
        $generatedUsername = $validated['company_name'];

        // Validate uniqueness of generated username
        if (User::where('username', $generatedUsername)->exists()) {
            return back()->withErrors(['company_name' => 'This company name generates a username that is already taken. Please use a different name.'])->withInput();
        }

        DB::transaction(function () use ($request, $validated, $generatedUsername, $defaultPassword) {
            // Create Company Admin User with default password
            $user = User::create([
                'username'      => $generatedUsername,
                'email'         => $validated['email'] ?? null,
                'phone'         => $request->phone ?? null,
                'password'      => Hash::make($defaultPassword),
                'role_id'       => 2, // Company Admin
                'superadmin_id' => auth()->id(), // Superadmin who created this
                'company_id'    => null, // Will be set to user's own id after creation
            ]);

            // company_id = Company Admin ka users.id (users TABLE is MAIN)
            $user->update(['company_id' => $user->id]);

            // Create Company Record (just for profile data)
            $company = Company::create(array_merge($request->except(['_token', 'username', 'password']), [
                'user_id'       => $user->id,        // Link to the Company Admin user
                'superadmin_id' => auth()->id()      // Link to Superadmin who created it
            ]));

            // Create Main Branch - company_id = users.id of role_id=2
            \App\Models\Branch::create([
                'company_id'    => $user->id,        // users.id of role_id=2
                'superadmin_id' => auth()->id(),
                'name'          => 'Main Branch'
            ]);

            // Create Demo Department - company_id = users.id of role_id=2
            \App\Models\Department::create([
                'company_id'    => $user->id,        // users.id of role_id=2
                'superadmin_id' => auth()->id(),
                'name'          => 'Software Development',
                'head_email'    => $validated['email'] ?? null
            ]);

            // Switch active company context to this new company
            session(['active_company_id' => $user->id]);
        });

        return redirect()->route('company.index')->with('success', 'Company created! Default login password is: 123456');
    }

    public function edit($id)
    {
        if (auth()->user()->role_id != 1) {
            abort(403, 'Unauthorized');
        }

        $company = Company::findOrFail($id);
        return view('admin.company.edit', compact('company'));
    }

    public function update(Request $request, $id)
    {
        if (auth()->user()->role_id != 1) {
            abort(403, 'Unauthorized');
        }

        $company = Company::findOrFail($id);

        $request->validate([
            'company_name'    => 'required|string|max:255',
            'company_address' => 'required|string|max:255',
            'email'           => 'nullable|email|max:255',
        ]);

        $company->update($request->except(['_token', '_method']));

        $generatedUsername = $request->company_name;

        $userUpdateData = [
            'email' => $request->email,
            'phone' => $request->phone,
            'username' => $generatedUsername,
        ];

        if ($request->filled('password')) {
            $userUpdateData['password'] = Hash::make($request->password);
        }

        if ($company->user_id) {
            User::where('id', $company->user_id)->update($userUpdateData);
        }

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

    public function destroy($id)
    {
        if (auth()->user()->role_id != 1) {
            abort(403, 'Unauthorized');
        }

        $company = Company::findOrFail($id);

        DB::transaction(function () use ($company) {
            // company->user_id = Company Admin ka users.id (role_id=2)
            // branches.company_id = users.id of role_id=2 (NOT companies.id)
            $companyAdminUserId = $company->user_id;

            // Delete Branches
            \App\Models\Branch::where('company_id', $companyAdminUserId)->delete();

            // Delete Departments
            \App\Models\Department::where('company_id', $companyAdminUserId)->delete();

            // Delete associated Company Admin user (this also removes all employees via cascade)
            if ($company->user_id) {
                User::where('id', $company->user_id)->delete();
            }

            // Delete company record
            $company->delete();
        });

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