<?php

namespace App\Http\Controllers\HRM;

use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\Company;
use App\Models\Department;
use App\Models\Employee;
use App\Models\EmployeeDocument;
use App\Models\JobTitle;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class EmployeeController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $companyId = $request->session()->get('company_id');
        $query = Employee::with(['department', 'jobTitle', 'branch'])
            ->where('company_id', $companyId);

        // Apply filters if provided
        if ($request->has('status') && $request->status != '') {
            $query->where('status', $request->status);
        }

        if ($request->has('department_id') && $request->department_id != '') {
            $query->where('department_id', $request->department_id);
        }

        if ($request->has('branch_id') && $request->branch_id != '') {
            $query->where('branch_id', $request->branch_id);
        }

        if ($request->has('search') && $request->search != '') {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('first_name', 'like', "%{$search}%")
                    ->orWhere('last_name', 'like', "%{$search}%")
                    ->orWhere('first_name_en', 'like', "%{$search}%")
                    ->orWhere('last_name_en', 'like', "%{$search}%")
                    ->orWhere('employee_number', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%");
            });
        }

        $employees = $query->paginate(10);
        $departments = Department::where('company_id', $companyId)->get();
        $branches = Branch::where('company_id', $companyId)->get();

        return view('hrm.employees.index', compact('employees', 'departments', 'branches'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(Request $request)
    {
        $companyId = $request->session()->get('company_id');
        $departments = Department::where('company_id', $companyId)->get();
        $branches = Branch::where('company_id', $companyId)->get();
        $jobTitles = JobTitle::where('company_id', $companyId)->get();

        // تقييد المستخدمين بالشركة الحالية فقط
        $users = User::where('company_id', $companyId)
            ->whereDoesntHave('employee')
            ->get();

        return view('hrm.employees.create', compact('departments', 'branches', 'jobTitles', 'users'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $companyId = $request->session()->get('company_id');

        $validator = Validator::make($request->all(), [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'employee_number' => [
                'required',
                'string',
                'max:50',
                function ($attribute, $value, $fail) use ($companyId) {
                    // Check if employee_number is unique within the company
                    $exists = Employee::where('employee_number', $value)
                        ->where('company_id', $companyId)
                        ->exists();

                    if ($exists) {
                        $fail('قيمة employee number مُستخدمة من قبل في هذه الشركة.');
                    }
                },
            ],
            'department_id' => 'nullable|exists:departments,id',
            'branch_id' => 'nullable|exists:branches,id',
            'job_title_id' => 'nullable|exists:job_titles,id',
            'user_id' => 'nullable|exists:users,id',
            'join_date' => 'required|date',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:20',
            'profile_picture' => 'nullable|image|max:2048',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $companyId = $request->session()->get('company_id');
        $data = $request->all();
        $data['company_id'] = $companyId;
        $data['created_by'] = Auth::id();

        // Handle profile picture upload
        if ($request->hasFile('profile_picture')) {
            $path = $request->file('profile_picture')->store('employees/profile_pictures', 'public');
            $data['profile_picture'] = $path;
        }

        // Handle skills as JSON
        if ($request->has('skills')) {
            $data['skills'] = json_encode(explode(',', $request->skills));
        }

        $employee = Employee::create($data);

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

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $employee = Employee::with(['department', 'jobTitle', 'branch', 'user', 'documents', 'attendances', 'leaves', 'salaries'])
            ->findOrFail($id);

        // Check if employee belongs to the current company
        $companyId = session('company_id');
        if ($employee->company_id != $companyId) {
            abort(403, 'Unauthorized action.');
        }

        return view('hrm.employees.show', compact('employee'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request, $id)
    {
        $companyId = $request->session()->get('company_id');
        $employee = Employee::findOrFail($id);

        // Check if employee belongs to the current company
        if ($employee->company_id != $companyId) {
            abort(403, 'Unauthorized action.');
        }

        $departments = Department::where('company_id', $companyId)->get();
        $branches = Branch::where('company_id', $companyId)->get();
        $jobTitles = JobTitle::where('company_id', $companyId)->get();

        // تقييد المستخدمين بالشركة الحالية فقط
        $users = User::where(function ($query) use ($employee) {
            $query->whereDoesntHave('employee')
                ->orWhere('id', $employee->user_id);
        })
            ->where('company_id', $companyId)
            ->get();

        return view('hrm.employees.edit', compact('employee', 'departments', 'branches', 'jobTitles', 'users'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $employee = Employee::findOrFail($id);

        // Check if employee belongs to the current company
        $companyId = $request->session()->get('company_id');
        if ($employee->company_id != $companyId) {
            abort(403, 'Unauthorized action.');
        }

        $validator = Validator::make($request->all(), [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'employee_number' => [
                'required',
                'string',
                'max:50',
                function ($attribute, $value, $fail) use ($companyId, $id) {
                    // Check if employee_number is unique within the company (excluding current employee)
                    $exists = Employee::where('employee_number', $value)
                        ->where('company_id', $companyId)
                        ->where('id', '!=', $id)
                        ->exists();

                    if ($exists) {
                        $fail('قيمة employee number مُستخدمة من قبل في هذه الشركة.');
                    }
                },
            ],
            'department_id' => 'nullable|exists:departments,id',
            'branch_id' => 'nullable|exists:branches,id',
            'job_title_id' => 'nullable|exists:job_titles,id',
            'user_id' => 'nullable|exists:users,id',
            'join_date' => 'required|date',
            'email' => 'nullable|email|max:255',
            'phone' => 'nullable|string|max:20',
            'profile_picture' => 'nullable|image|max:2048',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $data = $request->all();
        $data['updated_by'] = Auth::id();

        // Handle profile picture upload
        if ($request->hasFile('profile_picture')) {
            // Delete old profile picture if exists
            if ($employee->profile_picture) {
                Storage::disk('public')->delete($employee->profile_picture);
            }

            $path = $request->file('profile_picture')->store('employees/profile_pictures', 'public');
            $data['profile_picture'] = $path;
        }

        // Handle skills as JSON
        if ($request->has('skills')) {
            $data['skills'] = json_encode(explode(',', $request->skills));
        }

        $employee->update($data);

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

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(Request $request, $id)
    {
        $employee = Employee::findOrFail($id);

        // Check if employee belongs to the current company
        $companyId = $request->session()->get('company_id');
        if ($employee->company_id != $companyId) {
            abort(403, 'Unauthorized action.');
        }

        // Delete profile picture if exists
        if ($employee->profile_picture) {
            Storage::disk('public')->delete($employee->profile_picture);
        }

        $employee->delete();

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

    /**
     * Upload employee document.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function uploadDocument(Request $request, $id)
    {
        $employee = Employee::findOrFail($id);

        // Check if employee belongs to the current company
        $companyId = $request->session()->get('company_id');
        if ($employee->company_id != $companyId) {
            abort(403, 'Unauthorized action.');
        }

        $validator = Validator::make($request->all(), [
            'document_type' => 'required|string|max:255',
            'title' => 'required|string|max:255',
            'file' => 'required|file|max:10240', // 10MB max
            'expiry_date' => 'nullable|date',
            'notes' => 'nullable|string',
        ]);

        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $path = $request->file('file')->store('employees/documents', 'public');

        EmployeeDocument::create([
            'company_id' => $companyId,
            'employee_id' => $id,
            'document_type' => $request->document_type,
            'title' => $request->title,
            'file_path' => $path,
            'expiry_date' => $request->expiry_date,
            'notes' => $request->notes,
            'created_by' => Auth::id(),
        ]);

        return redirect()->route('hrm.employees.show', $id)
            ->with('success', 'Document uploaded successfully.');
    }

    /**
     * Delete employee document.
     *
     * @param  int  $documentId
     * @return \Illuminate\Http\Response
     */
    public function deleteDocument(Request $request, $documentId)
    {
        $document = EmployeeDocument::findOrFail($documentId);

        // Check if document belongs to the current company
        $companyId = $request->session()->get('company_id');
        if ($document->company_id != $companyId) {
            abort(403, 'Unauthorized action.');
        }

        $employeeId = $document->employee_id;

        // Delete file from storage
        Storage::disk('public')->delete($document->file_path);

        $document->delete();

        return redirect()->route('hrm.employees.show', $employeeId)
            ->with('success', 'Document deleted successfully.');
    }
}
