<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Employee;
use App\Models\User;
use App\Models\Branch;
use App\Models\Department;
use App\Models\Designation;
use App\Models\Policy;
use App\Models\Shift;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class EmployeeController extends Controller
{
    public function index()
    {
        $activeCompanyId = session('active_company_id');
        $employees = Employee::where('company_id', $activeCompanyId)->get();
        return view('admin.employees.index', compact('employees'));
    }

    public function create()
    {
        $activeCompanyId = session('active_company_id');
        if (!$activeCompanyId) {
            return redirect()->route('company.create')->withErrors(['company_name' => 'Please select or create a company first.']);
        }

        $branches = Branch::where('company_id', $activeCompanyId)->get();
        $departments = Department::where('company_id', $activeCompanyId)->get();
        $designations = Designation::where('company_id', $activeCompanyId)->get();
        $policies = Policy::where('company_id', $activeCompanyId)->get();
        $shifts = Shift::where('company_id', $activeCompanyId)->get();

        return view('admin.employees.create', compact('branches', 'departments', 'designations', 'policies', 'shifts'));
    }

    public function store(Request $request)
    {
        $activeCompanyId = session('active_company_id');
        if (!$activeCompanyId) abort(403, 'No active company selected.');

        $data = $request->except(['_token', 'photo']);

        $data['company_id'] = $activeCompanyId;
        $data['superadmin_id'] = \App\Models\User::find($activeCompanyId)->superadmin_id ?? auth()->id();
        $data['allow_notifications'] = $request->has('allow_notifications');
        $data['second_wo_days'] = $request->input('second_wo_days', []);
        $data['is_auto_shift'] = $request->input('is_auto_shift', []);

        DB::transaction(function () use ($request, &$data, $activeCompanyId) {
            // 1. Create User login for Employee
            // We use email or generate a username.
            // Get the company admin user ID from the company record
            $companyAdminUserId = $activeCompanyId; // active_company_id IS already the company admin users.id

            $user = User::create([
                'username'         => $data['name'],
                'email'            => $data['email'],
                'phone'            => $data['mobile_no'] ?? null,
                'password'         => Hash::make('password123'),
                'role_id'          => 3,
                'superadmin_id'    => \App\Models\User::find($activeCompanyId)->superadmin_id ?? auth()->id(),
                'company_admin_id' => $companyAdminUserId, // role_id=2 user ka ID
                'company_id'       => $activeCompanyId,
            ]);

            $data['user_id'] = $user->id;

            // 2. Handle Photo Upload
            if ($request->hasFile('photo')) {
                $path = $request->file('photo')->store('employees', 'public');
                $data['photo'] = $path;
            }

            // 3. Create Employee
            Employee::create($data);
        });

        return redirect()->route('employees.index')->with('success', 'Employee created successfully with a user account!');
    }

    public function edit($id)
    {
        $activeCompanyId = session('active_company_id');
        $employee = Employee::findOrFail($id);

        if ($employee->company_id != $activeCompanyId) {
            abort(403, 'Unauthorized action.');
        }

        $branches = Branch::where('company_id', $activeCompanyId)->get();
        $departments = Department::where('company_id', $activeCompanyId)->get();
        $designations = Designation::where('company_id', $activeCompanyId)->get();
        $policies = Policy::where('company_id', $activeCompanyId)->get();
        $shifts = Shift::where('company_id', $activeCompanyId)->get();

        return view('admin.employees.edit', compact('employee', 'branches', 'departments', 'designations', 'policies', 'shifts'));
    }

    public function update(Request $request, $id)
    {
        $activeCompanyId = session('active_company_id');
        $employee = Employee::findOrFail($id);

        if ($employee->company_id != $activeCompanyId) {
            abort(403, 'Unauthorized action.');
        }

        $data = $request->except(['_token', '_method', 'photo']);
        
        $data['allow_notifications'] = $request->has('allow_notifications');
        $data['second_wo_days'] = $request->input('second_wo_days', []);
        $data['is_auto_shift'] = $request->input('is_auto_shift', []);

        if ($request->hasFile('photo')) {
            // Delete old photo if exists
            if ($employee->photo) {
                Storage::disk('public')->delete($employee->photo);
            }
            $path = $request->file('photo')->store('employees', 'public');
            $data['photo'] = $path;
        }

        $employee->update($data);
        
        // Update User info if necessary
        if ($employee->user_id) {
            $user = User::find($employee->user_id);
            if ($user) {
                $user->update([
                    'username' => $data['name'],
                    'email' => $data['email'],
                    'phone' => $data['mobile_no'] ?? null,
                ]);
            }
        }

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

    public function salarySetup($id)
    {
        $activeCompanyId = session('active_company_id');
        $employee = Employee::findOrFail($id);

        if ($employee->company_id != $activeCompanyId) {
            abort(403, 'Unauthorized action.');
        }

        $company = \App\Models\Company::where('user_id', $activeCompanyId)->firstOrFail();
        $salarySetup = \App\Models\EmployeeSalarySetup::where('user_id', $employee->user_id)->first();

        return view('admin.employees.salary_setup', compact('employee', 'company', 'salarySetup'));
    }

    public function storeSalarySetup(Request $request, $id)
    {
        $activeCompanyId = session('active_company_id');
        $employee = Employee::findOrFail($id);

        if ($employee->company_id != $activeCompanyId) {
            abort(403, 'Unauthorized action.');
        }

        $data = $request->except(['_token']);
        
        // Checkboxes handling
        $data['show_overtime'] = $request->has('show_overtime');
        $data['show_weekoff'] = $request->has('show_weekoff');
        $data['pf_on_limit'] = $request->has('pf_on_limit');
        
        for ($i = 1; $i <= 8; $i++) {
            $data['is_esi_'.$i] = $request->has('is_esi_'.$i);
            $data['is_pf_'.$i] = $request->has('is_pf_'.$i);
            $data['is_ot_'.$i] = $request->has('is_ot_'.$i);
        }

        $data['company_id'] = $activeCompanyId;
        $data['user_id'] = $employee->user_id;

        \App\Models\EmployeeSalarySetup::updateOrCreate(
            ['user_id' => $employee->user_id, 'company_id' => $activeCompanyId],
            $data
        );

        return redirect()->route('employees.index')->with('success', 'Salary setup saved successfully!');
    }

    public function destroy($id)
    {
        $activeCompanyId = session('active_company_id');
        $employee = Employee::findOrFail($id);

        if ($employee->company_id != $activeCompanyId) {
            abort(403, 'Unauthorized action.');
        }

        // Delete associated user
        if ($employee->user_id) {
            User::where('id', $employee->user_id)->delete();
        }

        // Delete photo
        if ($employee->photo) {
            Storage::disk('public')->delete($employee->photo);
        }

        $employee->delete();
        return redirect()->route('employees.index')->with('success', 'Employee and associated user deleted successfully!');
    }
}
