<?php

namespace Modules\MedOrganization\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\MedOrganization\Entities\OrgUserDepartment;
use Yajra\DataTables\Facades\DataTables;

/**
 * Staff ↔ department assignments (spec §5 user_management "to_department:
 * many-to-many" + primary flag). Backs OrgScope::departmentIds().
 * Gated by medorg.department.manage (no dedicated permission in the brief —
 * flagged in the module docs).
 */
class StaffAssignmentController extends MedOrgBaseController
{
    public function index()
    {
        $this->guard('medorg.department.manage');

        if (request()->ajax()) {
            $rows = DB::table('org_user_departments as ud')
                ->join('users as u', 'u.id', '=', 'ud.user_id')
                ->join('clc_departments as d', 'd.id', '=', 'ud.department_id')
                ->where('ud.business_id', $this->businessId())
                ->select([
                    'ud.id', 'ud.is_primary',
                    DB::raw("TRIM(CONCAT(COALESCE(u.surname, ''), ' ', COALESCE(u.first_name, ''), ' ', COALESCE(u.last_name, ''))) as user_name"),
                    'u.username', 'd.name as department_name',
                ]);

            return DataTables::of($rows)
                ->editColumn('is_primary', fn ($r) => $r->is_primary
                    ? '<span class="label label-success">' . __('medorganization::lang.primary') . '</span>'
                    : '<span class="label label-default">' . __('medorganization::lang.secondary') . '</span>')
                ->addColumn('action', function ($r) {
                    $btns = '';
                    if (! $r->is_primary) {
                        $btns .= '<button data-href="' . route('medorg.staff-assignments.primary', $r->id) . '" class="btn btn-xs btn-info medorg-post-btn"><i class="fa fa-star"></i> ' . __('medorganization::lang.make_primary') . '</button> ';
                    }
                    $btns .= '<button data-href="' . route('medorg.staff-assignments.destroy', $r->id) . '" class="btn btn-xs btn-danger medorg-delete"><i class="fa fa-trash"></i></button>';

                    return $btns;
                })
                ->rawColumns(['is_primary', 'action'])
                ->make(true);
        }

        return view('medorganization::staff_assignments.index');
    }

    public function create()
    {
        $this->guard('medorg.department.manage');

        return view('medorganization::staff_assignments.create', [
            'users'       => \App\User::forDropdown($this->businessId(), false),
            'departments' => $this->departments(),
        ]);
    }

    public function store(Request $request)
    {
        $this->guard('medorg.department.manage');

        $data = $this->validate($request, [
            'user_id'       => 'required|integer',
            'department_id' => 'required|integer',
            'is_primary'    => 'nullable',
        ]);

        try {
            $bid = $this->businessId();

            $userOwned = DB::table('users')->where('business_id', $bid)->where('id', $data['user_id'])->exists();
            $deptOwned = DB::table('clc_departments')->where('business_id', $bid)->where('id', $data['department_id'])->exists();
            if (! $userOwned || ! $deptOwned) {
                abort(403, 'Unauthorized action.');
            }

            $isPrimary = $request->boolean('is_primary');

            DB::transaction(function () use ($bid, $data, $isPrimary) {
                if ($isPrimary) {
                    OrgUserDepartment::forBusiness($bid)
                        ->where('user_id', $data['user_id'])
                        ->update(['is_primary' => false]);
                }

                OrgUserDepartment::updateOrCreate(
                    ['user_id' => $data['user_id'], 'department_id' => $data['department_id']],
                    ['business_id' => $bid, 'is_primary' => $isPrimary]
                );
            });

            return $this->ok(__('medorganization::lang.added_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    /** Make this assignment the user's primary department. */
    public function setPrimary($id)
    {
        $this->guard('medorg.department.manage');

        try {
            $bid = $this->businessId();
            $assignment = OrgUserDepartment::forBusiness($bid)->findOrFail($id);

            DB::transaction(function () use ($bid, $assignment) {
                OrgUserDepartment::forBusiness($bid)
                    ->where('user_id', $assignment->user_id)
                    ->update(['is_primary' => false]);
                $assignment->update(['is_primary' => true]);
            });

            return $this->ok(__('medorganization::lang.updated_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }

    public function destroy($id)
    {
        $this->guard('medorg.department.manage');

        try {
            OrgUserDepartment::forBusiness($this->businessId())->findOrFail($id)->delete();

            return $this->ok(__('medorganization::lang.deleted_success'));
        } catch (\Exception $e) {
            \Log::emergency($e->getMessage());

            return $this->fail();
        }
    }
}
