<?php

namespace App\Http\Controllers;

use App\Models\Banking;
use App\Models\Child;
use App\Models\Company;
use App\Models\Education;
use App\Models\EmploymentHistory;
use App\Models\MedicalDeclaration;
use App\Models\MedicalHistory;
use App\Models\Spouse;
use App\Models\Staff;
use App\Models\StaffAddress;
use App\Models\StaffFile;
use App\Models\StaffPhone;
use App\Models\StaffSeparation;
use App\Models\StaffTraining;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use Inertia\Response;

class StaffController extends Controller
{
    public function index(Request $request): Response
    {
        $user      = Auth::user();
        $companyId = $user->company_id;

        $query = Staff::with('company', 'department')
            ->orderBy('full_name');

        if ($user->isCompanyHr() && $companyId) {
            $query->where('company_id', $companyId);
        }

        if ($request->filled('search')) {
            $search = '%' . $request->search . '%';
            $query->where(function ($q) use ($search) {
                $q->where('full_name', 'like', $search)
                    ->orWhere('staff_no', 'like', $search)
                    ->orWhere('ic_no', 'like', $search)
                    ->orWhere('email', 'like', $search)
                    ->orWhere('job_title', 'like', $search);
            });
        }

        if ($request->filled('company_id') && $user->isSuperAdmin()) {
            $query->where('company_id', $request->company_id);
        }

        if ($request->filled('status')) {
            $query->where('status', $request->status);
        }

        $staff    = $query->paginate(20)->withQueryString();
        $companies = $user->isSuperAdmin() ? Company::orderBy('name')->get(['id', 'name']) : [];

        return Inertia::render('Staff/Index', [
            'staff'     => $staff,
            'companies' => $companies,
            'filters'   => $request->only(['search', 'company_id', 'status']),
        ]);
    }

    public function show(Staff $staff): Response
    {
        $user = Auth::user();

        if ($user->isCompanyHr() && $user->company_id && $staff->company_id !== $user->company_id) {
            abort(403);
        }

        $staff->load('company', 'department', 'unit');

        $education           = Education::where('staff_id', $staff->id)->orderByDesc('end_date')->get();
        $banking             = Banking::where('staff_id', $staff->id)->orderByDesc('is_primary')->get();
        $spouses             = Spouse::where('staff_id', $staff->id)->get();
        $children            = Child::where('staff_id', $staff->id)->orderBy('date_of_birth')->get();
        $files               = StaffFile::where('staff_id', $staff->id)->orderByDesc('created_at')->get();
        $employmentHistory   = EmploymentHistory::where('staff_id', $staff->id)->orderByDesc('start_date')->get();
        $training            = StaffTraining::where('staff_id', $staff->id)->orderByDesc('start_date')->get();
        $medicalHistory      = MedicalHistory::where('staff_id', $staff->id)->orderByDesc('diagnosed_date')->get();
        $medicalDeclarations = MedicalDeclaration::where('staff_id', $staff->id)->orderByDesc('declaration_date')->get();
        $addresses           = StaffAddress::where('staff_id', $staff->id)->get();
        $phones              = StaffPhone::where('staff_id', $staff->id)->get();
        $separations         = StaffSeparation::where('staff_id', $staff->id)->orderByDesc('effective_date')->get();

        $selfServiceUrl = $staff->self_service_token
            ? url('/hr-portal/self-service/' . $staff->self_service_token)
            : null;

        return Inertia::render('Staff/Show', [
            'staff'               => $staff,
            'education'           => $education,
            'banking'             => $banking,
            'spouses'             => $spouses,
            'children'            => $children,
            'files'               => $files,
            'employmentHistory'   => $employmentHistory,
            'training'            => $training,
            'medicalHistory'      => $medicalHistory,
            'medicalDeclarations' => $medicalDeclarations,
            'addresses'           => $addresses,
            'phones'              => $phones,
            'separations'         => $separations,
            'selfServiceUrl'      => $selfServiceUrl,
        ]);
    }

    public function generateSelfServiceToken(Staff $staff)
    {
        $user = Auth::user();

        if ($user->isCompanyHr() && $user->company_id && $staff->company_id !== $user->company_id) {
            abort(403);
        }

        $token = 'sst-' . bin2hex(random_bytes(16));
        $staff->update(['self_service_token' => $token]);

        return redirect()->back()->with('success', 'Self-service link generated.');
    }
}
