<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Campus;
use App\Http\Requests\CampusRequest;
use App\Http\Resources\CampusResource;
use App\Models\SourceType;
use App\Services\MediaService;

class CampusController extends Controller
{    
    /**
     * get
     *
     * @param  mixed $request
     * @return void
     */
    public function get(Request $request){
        $campuses = Campus::all();
        return response()->json([ 'campuses' => CampusResource::collection($campuses) ]);
    }


    public function create(CampusRequest $request){

        $campus = new Campus();
        $campus->code = $request->code;
        $campus->address = $request->address;        
        $campus->title = $request->title;        
        $campus->email = $request->email;   
        $campus->manager_id = $request->manager_id;     
        $campus->contacts = ['primary' => $request->phone, 'secondary' => $request->secondary_phone ?? ""];        
        $campus->save();
        $image_path = MediaService::get_image_path($request);        
        if($image_path){
            $image_path['mediable_id']     = $campus->id;
            $image_path['mediable_type']   = SourceType::CAMPUS;
            MediaService::create($image_path);
        }

        $documents = MediaService::get_documents_path($request);
        if(count($documents) > 0){
            foreach($documents as $doc){
                $doc['mediable_id'] = $campus->id;
                $doc['mediable_type'] = SourceType::USER;
                MediaService::create($doc);
            }
        }
        
        return response()->json([ 'campus' => new CampusResource($campus) ]);
    }

}
