<?php

namespace Portal\Mileage\Http\Controllers;

use Portal\Mileage\Model\Project;
use Portal\Mileage\Model\JenisKenderaan;
use Portal\Mileage\Model\ProjectTeam;
use Portal\Mileage\Model\Users;

use Illuminate\Support\Facades\Auth;
use Illuminate\Routing\Controller;
use Illuminate\Http\Request;
use DB;

class ApplyformController extends Controller
{
    public function __construct()
    {
        //
    }

    /**
     * Build candidate IDs for current user
     */
    protected function getCandidateIds($user)
    {
        $candidates = [];

        // 1) user id
        if (!empty($user->id)) {
            $candidates[] = $user->id;
        }

        // 2) employeeCode on User model
        if (!empty($user->employeeCode)) {
            $candidates[] = $user->employeeCode;
        }

        // 3) extra lookup from portal Users table
        $portalUser = Users::where('id', $user->id)->first();
        if ($portalUser) {
            if (!empty($portalUser->employeeCode)) {
                $candidates[] = $portalUser->employeeCode;
            }
            if (!empty($portalUser->pt_staff_id)) {
                $candidates[] = $portalUser->pt_staff_id;
            }
        }

        // Clean up (remove nulls, duplicates)
        return array_values(array_unique(array_filter($candidates, function ($v) {
            return $v !== null && $v !== '';
        })));
    }

    /**
     * Get projects for the logged in user
     */
    protected function getProjectsForUser($user)
    {
        $candidates = $this->getCandidateIds($user);

        $projectIds = [];
        if (!empty($candidates)) {
            $projectIds = ProjectTeam::whereIn('pt_staff_id', $candidates)
                ->pluck('fk_project_id')
                ->unique()
                ->toArray();
        }

        $isAdmin = ($user->role_id == 1);

        if ($isAdmin) {
            // Admin sees all
            return Project::orderBy('p_project_description')->get();
        } elseif (!empty($projectIds)) {
            // Non-admin, but has assigned projects
            return Project::whereIn('id', $projectIds)
                ->orderBy('p_project_description')
                ->get();
        }

        // Non-admin with no assigned projects
        return collect([]);
    }

    public function index()
    {
        $user = auth()->user();

        // fetch role names directly
        $roles = $user->roles->pluck('name')->toArray();

        $isAdmin = in_array('Administrator', $roles); // check by role name

        if ($isAdmin) {
            // Admin → all projects
            $projects = Project::orderBy('p_project_description')->get();
        } else {
            // Non-admin → only their assigned projects
            $projects = Project::whereHas('projectTeam', function($q) use ($user) {
                $q->where('pt_staff_id', $user->employee_code);
            })->get();
        }

        $jenisKenderaan = JenisKenderaan::all();
        return view('mileage::applyform.index', compact('projects', 'jenisKenderaan'));
    }

    public function create()
    {
        $user = Auth::user();
        $projects = $this->getProjectsForUser($user);
        $jenisKenderaan = JenisKenderaan::all();

        return view('mileage::applyform.index', compact('projects', 'jenisKenderaan'));
    }

    public function save(Request $request)
    {
        // TODO: Implement save logic
        return null;
    }

    public function noproject()
    {
        $user = Auth::user();
        $jenisKenderaan = JenisKenderaan::all();
        
        return view('mileage::applyform.noproject', compact('jenisKenderaan'));
    }

}
