<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Branch;
use App\Models\Project;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;


class ProjectController extends Controller
{
    public function login(Request $request)
    {
        $credentials = $request->validate([
            'id' => 'required',
            'password' => 'required',
        ]);
        if (!$token = Auth::guard('api')->attempt($credentials)) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        if ($request->has('fcm_token')) {
            $fcm_token = $request->fcm_token;
        } else {
            $fcm_token = null;
        }
        return $this->respondWithToken($token, $fcm_token);
    }

    protected function respondWithToken($token, $fcm_token)
    {
        $project = Project::find(Auth::guard('api')->user()->id);
        $project->fcm_token = $fcm_token;
        $project->save();
        return response()->json([
            'project' => $project,
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => JWTAuth::factory()->getTTL() * 60
        ]);
    }

    public function getBranches()
    {
        $branches = Branch::select('id', 'name')->get();
        return response()->json(['success' => true, 'branches' => $branches]);
    }

    public function getProjects($branch_id)
    {
        $projects = Project::select('id', 'name', 'branch_id')->where('branch_id', $branch_id)->get();
        return response()->json(['success' => true, 'branches' => $projects]);
    }
}
