<?php

namespace App\Http\Controllers;

use App\Models\EmploymentHistory;
use App\Models\MedicalDeclaration;
use App\Models\MedicalHistory;
use App\Models\Staff;
use App\Models\StaffAddress;
use App\Models\StaffPhone;
use App\Models\StaffSeparation;
use App\Models\StaffTraining;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class StaffDetailController extends Controller
{
    private function authorizeStaff(Staff $staff): void
    {
        $user = Auth::user();
        if ($user->role === 'company_hr' && $user->company_id && $staff->company_id !== $user->company_id) {
            abort(403);
        }
    }

    // ── Employment History ─────────────────────────────────────────────────────
    public function storeEmploymentHistory(Request $request, Staff $staff)
    {
        $this->authorizeStaff($staff);
        $data = $request->validate([
            'job_title'       => 'required|string|max:255',
            'department'      => 'nullable|string',
            'employment_type' => 'nullable|string',
            'start_date'      => 'required|date',
            'end_date'        => 'nullable|date',
            'remarks'         => 'nullable|string',
        ]);
        $staff->employmentHistory()->create($data);
        return back()->with('success', 'Employment record added.');
    }

    public function destroyEmploymentHistory(Staff $staff, EmploymentHistory $record)
    {
        $this->authorizeStaff($staff);
        $record->delete();
        return back()->with('success', 'Record removed.');
    }

    // ── Training ───────────────────────────────────────────────────────────────
    public function storeTraining(Request $request, Staff $staff)
    {
        $this->authorizeStaff($staff);
        $data = $request->validate([
            'training_name'      => 'required|string|max:255',
            'provider'           => 'nullable|string',
            'training_type'      => 'nullable|string',
            'start_date'         => 'required|date',
            'end_date'           => 'nullable|date',
            'duration_hours'     => 'nullable|integer',
            'venue'              => 'nullable|string',
            'cost'               => 'nullable|numeric',
            'certificate_no'     => 'nullable|string',
            'certificate_expiry' => 'nullable|date',
            'status'             => 'nullable|string',
        ]);
        $staff->training()->create($data);
        return back()->with('success', 'Training record added.');
    }

    public function destroyTraining(Staff $staff, StaffTraining $record)
    {
        $this->authorizeStaff($staff);
        $record->delete();
        return back()->with('success', 'Training removed.');
    }

    // ── Medical History ────────────────────────────────────────────────────────
    public function storeMedicalHistory(Request $request, Staff $staff)
    {
        $this->authorizeStaff($staff);
        $data = $request->validate([
            'condition_name' => 'required|string|max:255',
            'diagnosed_date' => 'nullable|date',
            'treatment'      => 'nullable|string',
            'is_chronic'     => 'boolean',
            'notes'          => 'nullable|string',
        ]);
        $staff->medicalHistory()->create($data);
        return back()->with('success', 'Medical record added.');
    }

    public function destroyMedicalHistory(Staff $staff, MedicalHistory $record)
    {
        $this->authorizeStaff($staff);
        $record->delete();
        return back()->with('success', 'Record removed.');
    }

    // ── Medical Declaration ────────────────────────────────────────────────────
    public function storeMedicalDeclaration(Request $request, Staff $staff)
    {
        $this->authorizeStaff($staff);
        $data = $request->validate([
            'declaration_date'         => 'required|date',
            'has_pre_existing_conditions' => 'boolean',
            'conditions_detail'        => 'nullable|string',
            'is_fit_for_duty'          => 'boolean',
            'doctor_name'              => 'nullable|string',
            'clinic_name'              => 'nullable|string',
        ]);
        $staff->medicalDeclarations()->create($data);
        return back()->with('success', 'Declaration added.');
    }

    // ── Addresses ─────────────────────────────────────────────────────────────
    public function storeAddress(Request $request, Staff $staff)
    {
        $this->authorizeStaff($staff);
        $data = $request->validate([
            'label'      => 'nullable|string',
            'address'    => 'required|string',
            'city'       => 'nullable|string',
            'state'      => 'nullable|string',
            'postcode'   => 'nullable|string',
            'country'    => 'nullable|string',
            'is_current' => 'boolean',
        ]);
        $staff->addresses()->create($data);
        return back()->with('success', 'Address added.');
    }

    public function destroyAddress(Staff $staff, StaffAddress $address)
    {
        $this->authorizeStaff($staff);
        $address->delete();
        return back()->with('success', 'Address removed.');
    }

    // ── Phones ─────────────────────────────────────────────────────────────────
    public function storePhone(Request $request, Staff $staff)
    {
        $this->authorizeStaff($staff);
        $data = $request->validate([
            'phone'      => 'required|string',
            'type'       => 'nullable|string',
            'is_primary' => 'boolean',
        ]);
        $staff->phones()->create($data);
        return back()->with('success', 'Phone added.');
    }

    public function destroyPhone(Staff $staff, StaffPhone $phone)
    {
        $this->authorizeStaff($staff);
        $phone->delete();
        return back()->with('success', 'Phone removed.');
    }

    // ── Separation ─────────────────────────────────────────────────────────────
    public function storeSeparation(Request $request, Staff $staff)
    {
        $this->authorizeStaff($staff);
        $data = $request->validate([
            'separation_type'    => 'required|string',
            'last_working_day'   => 'required|date',
            'effective_date'     => 'required|date',
            'reason'             => 'nullable|string',
            'is_eligible_rehire' => 'boolean',
            'notice_period'      => 'nullable|string',
            'exit_remarks'       => 'nullable|string',
        ]);
        $data['approved_by'] = Auth::id();
        $staff->separations()->create($data);
        $staff->update(['status' => 'terminated']);
        return back()->with('success', 'Separation recorded. Staff status updated.');
    }
}
