<?php

namespace App\Http\Controllers;

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

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $validated = $request->validate([
            'company_name' => 'required|string',
            'company_address' => 'required|string',
            'email' => 'required|email|unique:users',
            'phone' => 'required|string',
            'corporate_id' => 'required|string|unique:superadmin_profiles,corporate_id',
            'username' => 'required|string|unique:users',
            'password' => 'required|string|min:6|confirmed',
            'partner_id' => 'nullable|string',
            'dealer_name' => 'nullable|string',
        ]);

        [$superadmin, $companyAdmin] = DB::transaction(function () use ($validated) {
            // 1. Create the Superadmin (role_id = 1) with login credentials
            $superadmin = User::create([
                'username' => $validated['username'],
                'email' => $validated['email'],
                'phone' => $validated['phone'],
                'password' => Hash::make($validated['password']),
                'role_id' => 1,
            ]);

            // 2. Save the rest of the form data to Superadmin Profile
            \App\Models\SuperadminProfile::create([
                'user_id' => $superadmin->id,
                'company_name' => $validated['company_name'],
                'company_address' => $validated['company_address'],
                'corporate_id' => $validated['corporate_id'],
                'email' => $validated['email'],
                'phone' => $validated['phone'],
                'partner_id' => $validated['partner_id'] ?? null,
                'dealer_name' => $validated['dealer_name'] ?? null,
            ]);
            // 3. Create a Demo Company Admin (role_id = 2)
            // Note: company_id will be updated after company creation
            $companyAdmin = User::create([
                'username' => 'demo',
                'email' => 'demo@example.com',
                'phone' => '0000000000',
                'password' => Hash::make('password'), // default password
                'role_id' => 2,
                'superadmin_id' => $superadmin->id,
            ]);

            // 4. Create a Demo Company in the companies table
            $company = Company::create([
                'user_id' => $companyAdmin->id, // Link to the Company Admin
                'superadmin_id' => $superadmin->id, // Link to the Superadmin who created it
                'company_name' => 'Demo',
                'company_address' => 'Demo',
                'corporate_id' => null,
                'email' => null,
                'phone' => null,
                'partner_id' => null,
                'dealer_name' => null,
            ]);

            // NOTE: company_id ab companies.id NAHI hai
            // company_id = Company Admin ka users.id (role_id=2) - users TABLE MAIN HAI

            // Update Company Admin user with company_id = their OWN users.id (self-reference for role=2)
            // No update needed - company_id in role=2 user = their own id (set below via session)
            // The companies table just stores the profile data

            // 5. Create a Default Head Office / Main Branch
            $branch = \App\Models\Branch::create([
                'company_id' => $companyAdmin->id, // users.id of role_id=2
                'superadmin_id' => $superadmin->id,
                'name' => 'Main Branch'
            ]);

            // 6. Create Demo Department
            $department = \App\Models\Department::create([
                'company_id' => $companyAdmin->id, // users.id of role_id=2
                'superadmin_id' => $superadmin->id,
                'name' => 'Demo',
                'head_email' => $validated['email']
            ]);

            // 7. Create Demo Designation
            $designation = \App\Models\Designation::create([
                'company_id' => $companyAdmin->id, // users.id of role_id=2
                'superadmin_id' => $superadmin->id,
                // 'department_id' => $department->id,
                'name' => 'Demo Designation'
            ]);

            // 8. Create a Dummy Employee User (role_id = 3)
            $employeeUser = User::create([
                'username' => 'demo_employee',
                'email' => 'employee@demo.com',
                'phone' => '1111111111',
                'password' => Hash::make('password'),
                'role_id' => 3,
                'superadmin_id' => $superadmin->id,    // role_id=1 ka users.id
                'company_admin_id' => $companyAdmin->id,  // role_id=2 ka users.id
                'company_id' => $companyAdmin->id,  // users.id of role_id=2 (MAIN TABLE)
            ]);

            // 9. Create the Dummy Employee
            \App\Models\Employee::create([
                'company_id' => $companyAdmin->id,  // users.id of role_id=2
                'superadmin_id' => $superadmin->id,
                'user_id' => $employeeUser->id,
                'employee_code' => 'EMP-001',
                'name' => 'Demo Employee',
                'email' => 'employee@demo.com',
                'mobile_no' => '1111111111',
                'branch_id' => $branch->id,
                'department_id' => $department->id,
                'designation_id' => $designation->id,
                'joining_date' => now()->format('Y-m-d'),
                'is_active' => true,
            ]);

            // Return both so they are accessible outside the transaction
            return [$superadmin, $companyAdmin];
        });

        Auth::login($superadmin);

        // active_company_id = Company Admin ka users.id (role_id=2)
        // This is the MAIN id used in branches, departments, employees etc.
        // (users TABLE is MAIN - not companies table)
        session(['active_company_id' => $companyAdmin->id ?? null]);

        return redirect('/admin/dashboard');
    }

    public function login(Request $request)
    {
        $request->validate([
            'corporate_id' => 'required|string',
            'username'     => 'required|string',
            'password'     => 'required|string',
        ]);

        // Step 1: Find user by username
        $user = User::where('username', $request->username)->first();

        if (!$user || !Hash::check($request->password, $user->password)) {
            return back()->withErrors([
                'username' => 'The provided credentials do not match our records.',
            ])->withInput($request->only('username', 'corporate_id'));
        }

        // Step 2: Verify corporate_id matches user's superadmin profile
        $profile = \App\Models\SuperadminProfile::where('user_id', $user->id)
            ->where('corporate_id', $request->corporate_id)
            ->first();

        if (!$profile) {
            return back()->withErrors([
                'username' => 'Invalid Corporate ID. Please check and try again.',
            ])->withInput($request->only('username', 'corporate_id'));
        }

        // Step 3: Only Superadmins (role_id = 1) can login via this panel
        if ($user->role_id !== 1) {
            return back()->withErrors([
                'username' => 'Only Superadmins can access the dashboard.',
            ]);
        }

        // Step 4: Login and set session
        Auth::login($user);
        $request->session()->regenerate();

        $firstCompany = Company::where('superadmin_id', $user->id)->first();
        if ($firstCompany) {
            session(['active_company_id' => $firstCompany->user_id]);
        }

        return redirect()->intended('/admin/dashboard');
    }

    public function getUserByPhone(Request $request)
    {
        $request->validate(['phone' => 'required|string']);

        $user = User::where('phone', $request->phone)->where('role_id', 1)->first();

        if ($user) {
            // corporate_id is in superadmin_profiles, not users table
            $profile = \App\Models\SuperadminProfile::where('user_id', $user->id)->first();

            return response()->json([
                'success'      => true,
                'corporate_id' => $profile ? $profile->corporate_id : null,
                'username'     => $user->username,
            ]);
        }

        return response()->json(['success' => false, 'message' => 'No user found with this mobile number.']);
    }

    public function logout(Request $request)
    {
        Auth::logout();

        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/login');
    }
}
