<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Employee;
use App\Models\Branch;
use Illuminate\Http\Request;

class EmployeeController extends Controller
{
    public function index()
    {
        $this->authorize('view_employees');
        $employees = Employee::with(['branches', 'jobTitle'])->latest()->paginate(15);
        return view('admin.employees.index', compact('employees'));
    }

    public function create()
    {
        $this->authorize('create_employees');
        $branches = Branch::where('status', 'active')->get();
        $jobTitles = \App\Models\JobTitle::where('active', true)->get();
        return view('admin.employees.create', compact('branches', 'jobTitles'));
    }

    public function store(Request $request)
    {
        $this->authorize('create_employees');
        $validated = $request->validate([
            'branch_ids' => 'required|array|min:1',
            'branch_ids.*' => 'exists:branches,id',
            'job_title_id' => 'required|exists:job_titles,id',
            'name' => 'required|string|max:255',
            'job_title' => 'nullable|string|max:255',
            'basic_salary' => 'required|numeric|min:0',
            'commission_rate' => 'nullable|numeric|min:0|max:100',
            'status' => 'required|in:active,inactive,on_leave',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'join_date' => 'nullable|date',
            'profile_image' => 'nullable|image|max:2048',
            'documents.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png,doc,docx|max:5120',
        ]);

        if ($request->hasFile('profile_image')) {
            $validated['profile_image'] = $request->file('profile_image')->store('employees/images', 'public');
        }

        if ($request->hasFile('documents')) {
            $docs = [];
            foreach ($request->file('documents') as $file) {
                $docs[] = $file->store('employees/documents', 'public');
            }
            $validated['documents'] = $docs;
        }

        $employee = Employee::create($validated);
        $employee->branches()->sync($request->branch_ids);

        return redirect()->route('admin.employees.index')->with('success', 'تم إضافة الموظف بنجاح.');
    }

    public function edit(Employee $employee)
    {
        $this->authorize('edit_employees');
        $branches = Branch::where('status', 'active')->get();
        $jobTitles = \App\Models\JobTitle::where('active', true)->get();
        return view('admin.employees.edit', compact('employee', 'branches', 'jobTitles'));
    }

    public function update(Request $request, Employee $employee)
    {
        $this->authorize('edit_employees');
        $validated = $request->validate([
            'branch_ids' => 'required|array|min:1',
            'branch_ids.*' => 'exists:branches,id',
            'job_title_id' => 'required|exists:job_titles,id',
            'name' => 'required|string|max:255',
            'job_title' => 'nullable|string|max:255',
            'basic_salary' => 'required|numeric|min:0',
            'commission_rate' => 'nullable|numeric|min:0|max:100',
            'status' => 'required|in:active,inactive,on_leave',
            'phone' => 'nullable|string|max:20',
            'email' => 'nullable|email|max:255',
            'join_date' => 'nullable|date',
            'profile_image' => 'nullable|image|max:2048',
            'documents.*' => 'nullable|file|mimes:pdf,jpg,jpeg,png,doc,docx|max:5120',
        ]);

        if ($request->hasFile('profile_image')) {
            if ($employee->profile_image) {
                \Illuminate\Support\Facades\Storage::disk('public')->delete($employee->profile_image);
            }
            $validated['profile_image'] = $request->file('profile_image')->store('employees/images', 'public');
        }

        if ($request->hasFile('documents')) {
            if ($employee->documents) {
                foreach ($employee->documents as $oldDoc) {
                    \Illuminate\Support\Facades\Storage::disk('public')->delete($oldDoc);
                }
            }
            $docs = [];
            foreach ($request->file('documents') as $file) {
                $docs[] = $file->store('employees/documents', 'public');
            }
            $validated['documents'] = $docs;
        }

        $employee->update($validated);
        $employee->branches()->sync($request->branch_ids);

        return redirect()->route('admin.employees.index')->with('success', 'تم تحديث بيانات الموظف بنجاح.');
    }

    public function destroy(Employee $employee)
    {
        $this->authorize('delete_employees');
        $employee->delete();
        return redirect()->route('admin.employees.index')->with('success', 'تم حذف الموظف بنجاح.');
    }
}
