<?php

namespace App\Http\Controllers;

use App\Models\Job_position;
use App\Models\Staff_member;
use App\Models\School_setting;
use App\Models\Staff_salary_struct;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Barryvdh\DomPDF\Facade\Pdf;

class StaffController extends Controller
{
    public function staff(Request $request)
    { 
        $staff = Staff_member::where('status', 'active');
      
        if ($request->filled('search_query')) {
            $staff->where(function ($query) use ($request) {
                $query->where('full_name', 'like', '%' . $request->search_query . '%')
                    ->orWhere('email', 'like', '%' . $request->search_query . '%')
                    ->orWhere('cnic', 'like', '%' . $request->search_query . '%');
            });
        }

        if ($request->filled('role_filter')) {
            $staff->where('position', $request->role_filter);
        }
        $staff = $staff->paginate(10);
        if ($request->ajax()) {
            return view('staff.staffSearch', compact('staff'))->render();
        }

        return view('staff.staff', compact('staff'));
    }

    public function staffPast(Request $request)
    {
        $staff = Staff_member::where('status', '=', 'resigned');
        // Apply search filter
        if ($request->filled('search_query')) {
            $staff->where(function ($query) use ($request) {
                $query->where('full_name', 'like', '%' . $request->search_query . '%')
                    ->orWhere('email', 'like', '%' . $request->search_query . '%')
                    ->orWhere('cnic', 'like', '%' . $request->search_query . '%');
            });
        }

        // Apply class filter if selected
        if ($request->filled('role_filter')) {
            $staff->where('position', $request->role_filter);
        }

        $staff = $staff->paginate(10);

        if ($request->ajax()) {
            return view('staff.partialPastStaff', compact('staff'))->render();
        }

        $roles = Staff_member::select('position')->distinct()->get();
        return view('staff.pastStaff', compact('staff', 'roles'));
    }

    public function profile($id)
    {
        $staff = Staff_member::findOrFail($id);
        return view('staff.staffProfile', compact('staff'));
    }

    public function edit($id)
    {
        $positions = Job_position::where('status', 'open')->get();
        $staff = Staff_member::findOrFail($id);
        return view('staff.editStaff', compact('staff', 'positions'));
    }

    public function create()
    {
        $positions = Job_position::where('status', 'open')->get();
        return view('staff.addStaff', compact('positions'));
    }

    public function update($id, Request $request)
    {
        $request->validate([
            'name'            => 'required|string|max:255',
            'fth_name'          => 'nullable|string|max:255',
            'email'                => 'required|email',
            'cnic'                 => 'required|string|max:20',
            'gender'               => 'required|string|max:10',
            'dob'        => 'nullable|date',
            'address'     => 'required|string',
            'primary_cont'   => 'required|string|max:20',
            'secondary_cont' => 'nullable|string|max:20',
            'position'             => 'required|string|max:255',
            'salary'               => 'nullable|numeric',
            'emp_type'      => 'required|string|max:255',
            'prev_exp'  => 'nullable|integer',
            'qualif'       => 'nullable|string',
            // 'photo'        => 'nullable|image|mimes:png,jpg,jpeg|max:5120',
            // 'cv'            => 'nullable|mimes:pdf,doc,docx|max:5120',
            // 'transcript'           => 'nullable|image|mimes:png,jpg,jpeg|max:5120',
            // 'degree'   => 'nullable|mimes:pdf,doc,docx|max:5120',
            'notes'     => 'nullable|string',
        ]);

        DB::beginTransaction();

        try {
            $staff = Staff_member::findOrFail($id);
            $staff->update([
                'full_name'            => $request->name,
                'father_name'          => $request->fth_name,
                'email'                => $request->email,
                'cnic'                 => $request->cnic,
                'gender'               => $request->gender,
                'date_of_birth'        => $request->dob,
                'address'     => $request->address,
                'primary_contact_no'   => $request->primary_cont,
                'secondary_contact_no' => $request->secondary_cont,
                'position'             => $request->position,
                'salary'               => $request->salary,
                'employment_type'      => $request->emp_type,
                'previous_experience'  => $request->prev_exp,
                'qualifications'       => $request->qualif,
                'additional_notes'     => $request->notes,
            ]);

            DB::commit();

            return redirect()->route('staff')->with('success', 'Updated successfully!');
        } catch (\Exception $e) {
            DB::rollback();
            return redirect()->back()->with('error', 'An error occurred while submitting the application. Please try again. ' . $e->getMessage());
        }
    }

    public function store(Request $request)
    {
        $request->validate([
            'name'            => 'required|string|max:255',
            'fth_name'        => 'nullable|string|max:255',
            'email'           => 'required|email',
            'cnic'            => 'required|string|max:20',
            'gender'          => 'required|string|max:10',
            'dob'             => 'nullable|date',
            'address'         => 'required|string',
            'primary_cont'    => 'required|string|max:20',
            'secondary_cont'  => 'nullable|string|max:20',
            'position'        => 'required|string|max:255',
            'salary'          => 'nullable|numeric',
            'emp_type'        => 'required|string|max:255',
            'prev_exp'        => 'nullable|integer',
            'qualif'          => 'nullable|string',
            'photo'           => 'nullable|image|mimes:png,jpg,jpeg',
            'cv'              => 'nullable|mimes:pdf,doc,docx',
            'transcript'      => 'nullable|image|mimes:png,jpg,jpeg',
            'degree'          => 'nullable|mimes:pdf,doc,docx',
            'notes'           => 'nullable|string',
        ]);

        // Manually check for duplicate CNIC
        $existing = Staff_member::where('cnic', $request->cnic)->first();
        if ($existing) {
            return redirect()->back()->withInput()->with('error', 'An employee with this CNIC already exists.');
        }

        DB::beginTransaction();

        try {
            // Handle file uploads
            $photoPath = $request->file('photo') ? $request->file('photo')->store('staff_members', 'public') : null;
            $cvPath = $request->file('cv') ? $request->file('cv')->store('staff_members', 'public') : null;
            $transPath = $request->file('transcript') ? $request->file('transcript')->store('staff_members', 'public') : null;
            $degPath = $request->file('degree') ? $request->file('degree')->store('staff_members', 'public') : null;

            $id = Staff_member::max('id') + 1;
            $headCode = '20200' . $id;

            $schoolName = School_setting::where('setting_key', 'school_name')->value('setting_value');
            $schoolPrefix = strtoupper(implode('', array_map(fn($word) => $word[0], explode(' ', $schoolName))));
            $reg_no = $schoolPrefix . str_pad($id, 2, '0', STR_PAD_LEFT);

            // Store staff
            $staffId = Staff_member::create([
                'user_id'              => null,
                'full_name'            => $request->name,
                'father_name'          => $request->fth_name,
                'head_code'            => $headCode,
                'registration_no'      => $reg_no,
                'email'                => $request->email,
                'cnic'                 => $request->cnic,
                'gender'               => $request->gender,
                'date_of_birth'        => $request->dob,
                'address'              => $request->address,
                'primary_contact_no'   => $request->primary_cont,
                'secondary_contact_no' => $request->secondary_cont,
                'position'             => $request->position,
                'salary'               => $request->salary,
                'employment_type'      => $request->emp_type,
                'previous_experience'  => $request->prev_exp,
                'qualifications'       => $request->qualif,
                'profile_photo'        => $photoPath,
                'cv_resume'            => $cvPath,
                'transcript'           => $transPath,
                'degree_certificate'   => $degPath,
                'additional_notes'     => $request->notes,
                'hire_date'            => now(),
                'status'               => 'active',
            ])->id;

            Staff_salary_struct::create([
                'staff_id' => $staffId,
                'head_code' => $headCode,
                'reg_no' => $reg_no,
                'salary' => $request->salary,
                'b1' => 0,
                'b2' => 0,
                'b3' => 0,
                'b4' => 0,
                'b5' => 0,
                'net_salary' => 0,
            ]);

            DB::commit();

            return redirect()->route('staff')->with('success', 'Staff successfully added!');
        } catch (\Exception $e) {
            DB::rollback();
            return redirect()->back()->with('error', 'An error occurred while submitting the application. Please try again. ' . $e->getMessage());
        }
    }

    public function updateStatus($id)
    {
        $staff = Staff_member::findOrFail($id);
        $staff->status = $staff->status === 'active' ? 'resigned' : 'active';
        $staff->save();

        return response()->json(['status' => $staff->status]);
    }

    public function exportActiveStaffPDF()
    {
        $staff = Staff_member::where('status', '!=', 'resigned')->get(); // No pagination or search

        $pdf = Pdf::loadView('staff.activeStaffListPdf', compact('staff'))->setPaper('A4', 'landscape');
        return $pdf->download('activeStaffList.pdf');
    }

    public function exportPastStaffPDF()
    {
        $staff = Staff_member::where('status', '!=', 'active')->get(); // No pagination or search

        $pdf = Pdf::loadView('staff.pastStaffListPdf', compact('staff'))->setPaper('A4', 'landscape');
        return $pdf->download('pastStaffList.pdf');
    }
}
