<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use App\Models\Offices;
use App\Models\OfficesDepartment;

class OfficesManageController extends Controller
{
    public function addOfficeDepartment(Request $request)
    {
        // Get all office IDs that are already assigned to a department head
        $usedOfficeIds = OfficesDepartment::pluck('office_department_id')->toArray();

        // Get only offices that are NOT already assigned
        $offices = Offices::whereNotIn('id', $usedOfficeIds)->select('id', 'description')->get();

        $data = [

            'offices' => $offices,
            'pageTitle' => 'Add new office department head'
        ];
        return view('back.pages.offices.add_office_department', $data);
    }
    public function createOfficeDepartment(Request $request)
    {
        $request->validate([
            'office_department_name'      => 'required|string',
            'office_department_position'  => 'required|string',
            'office_department_email' => 'required|email|unique:offices_departments,office_admin_email',
            'office_id'         => 'required|exists:offices,id',
            'office_head_image'     => 'nullable|image|mimes:jpg,jpeg,png|max:4096',
        ]);

        $new_filename = null;

        if ($request->hasFile('office_head_image')) {
            $path = 'images/office_admins/';
            $file = $request->file('office_head_image');
            $filename = $file->getClientOriginalName();
            $new_filename = time() . '_' . $filename;

            $upload = $file->move(public_path($path), $new_filename);

            if (!$upload) {
                return response()->json(['status' => 0, 'message' => 'Something went wrong on uploading the image.']);
            }
        }

        $officeDepartment = new OfficesDepartment();
        $officeDepartment->office_admin_name        = $request->office_department_name;
        $officeDepartment->office_admin_description = $request->office_department_position;
        $officeDepartment->office_admin_email       = $request->office_department_email;
        $officeDepartment->office_department_id     = $request->office_id;
        $officeDepartment->office_admin_image       = $new_filename;

        $saved = $officeDepartment->save();

        if ($saved) {
            return response()->json(['status' => 1, 'message' => 'Office Department Head has been successfully added.']);
        } else {
            return response()->json(['status' => 0, 'message' => 'Something went wrong while saving the record.']);
        }
    }

    public function getAvailableOffices()
    {
        $usedOfficeIds = OfficesDepartment::pluck('office_department_id')->toArray();
        $offices = Offices::whereNotIn('id', $usedOfficeIds)
            ->select('id', 'description')
            ->get();

        return response()->json($offices);
    }
    public function allOfficeDepartment(Request $request)
    {
        $data = [
            'pageTitle' => 'Office Department'
        ];
        return view('back.pages.offices.office_department', $data);
    }
    public function editOfficeDepartment(Request $request, $id = null)
    {
        $officeDepartment = OfficesDepartment::findOrFail($id); // ✅ this is the missing part

        $usedOfficeIds = OfficesDepartment::pluck('office_department_id')->toArray();

        // Get offices that are NOT already assigned OR the current one (so we don't block its own record)
        $offices = Offices::whereNotIn('id', $usedOfficeIds)
            ->orWhere('id', $officeDepartment->office_department_id) // ✅ include the current
            ->select('id', 'description')
            ->get();

        $data = [
            'offices' => $offices,
            'officeDepartment' => $officeDepartment, // ✅ pass this to view
            'pageTitle' => 'Edit office department head'
        ];

        return view('back.pages.offices.edit_office_department', $data);
    }
    public function updateOfficeDepartment(Request $request)
{
    try {
        $officeDepartment = OfficesDepartment::findOrFail($request->officeDepartment_id);
        $currentImage = $officeDepartment->office_admin_image;

        $request->validate([
            'office_department_name' => 'required|string',
            'office_department_position' => 'required|string',
            'office_department_email' => 'required|email',
            'office_head_image' => 'nullable|image|mimes:jpg,jpeg,png|max:4096',
        ]);

        if ($request->hasFile('office_head_image')) {
            $path = 'images/office_admins/';
            $file = $request->file('office_head_image');
            $filename = $file->getClientOriginalName();
            $newFilename = time() . '_' . $filename;

            // Delete old image if exists
            if ($currentImage && File::exists(public_path($path . $currentImage))) {
                File::delete(public_path($path . $currentImage));
            }

            // Save new image
            $file->move(public_path($path), $newFilename);
            $currentImage = $newFilename;
        }

        // Update fields
        $officeDepartment->office_admin_name = $request->office_department_name;
        $officeDepartment->office_admin_description = $request->office_department_position;
        $officeDepartment->office_admin_email = $request->office_department_email;
        $officeDepartment->office_admin_image = $currentImage;

        $saved = $officeDepartment->save();

        return response()->json([
            'status' => $saved ? 1 : 0,
            'message' => $saved ? 'Office Department Head successfully updated!' : 'Failed to update office department head.'
        ]);

    } catch (\Exception $e) {
        return response()->json([
            'status' => 0,
            'message' => 'Something went wrong. ' . $e->getMessage()
        ]);
    }
}

}
