<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\RoadConstructionProject;
use Illuminate\Support\Facades\Auth;

class RoadConstructionProjectController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $roadProjects = Auth::user()->roadConstructionProjects->all();

        return view('rmto-preview.pages.projects-list', ['roadProjects' => $roadProjects]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('rmto-preview.pages.road-construction');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $roadProject = new RoadConstructionProject;

        $roadProject->operation_type = $request['operationType_DB'];
        $roadProject->operation_sub_types = explode(',', $request['operationSubType_DB']);
        $roadProject->start_lat = $request['projectSourceCordLat_DB'] ?? null;
        $roadProject->start_lng = $request['projectSourceCordLng_DB'] ?? null;
        $roadProject->end_lat = $request['projectDestCordLat_DB'] ?? null;
        $roadProject->end_lng = $request['projectDestCordLng_DB'] ?? null;
        $roadProject->project_distance = $request['projectCalcDistance_DB'] ?? null;
        $roadProject->province = $request['selectedProvince_DB'] ?? null;
        $roadProject->city = $request['selectedTown_DB'] ?? null;
        $roadProject->axis_name = $request['projectAxis_DB'] ?? null;
        $roadProject->axis_type = $request['projectAxisType_DB'] ?? null;
        $roadProject->project_name = $request['projectName_DB'] ?? null;
        $roadProject->project_type = $request['projectType_DB'] ?? null;
        $roadProject->start_date = $request['projectStartDate_DB'] ?? null;
        $roadProject->consultant_name = $request['projectConsultantName_DB'] ?? null;
        $roadProject->contractor_name = $request['projectContractorName_DB'] ?? null;
        $roadProject->ordered_credit = $request['amountOrderCredit_DB'] ?? null;
        $roadProject->absorbed_credit = $request['amountAbsorbedCredit_DB'] ?? null;
        $roadProject->required_credit = $request['amountEndCredit_DB'] ?? null;
        $roadProject->plan_number = $request['projectPlanNumber_DB'] ?? null;
        //$roadProject->plan_office = $request[''];
        $roadProject->announced_date = $request['projectAnnouncedDate_DB'] ?? null;
        $roadProject->credit_progress = $request['projectRialSlider_DB'] ?? null;
        $roadProject->physical_progress = explode(',', $request['projectPhysicalSlider_DB']);
        $roadProject->project_problems = $request['projectProblem_DB'] ?? null;
        $roadProject->project_status = $request['projectStatus_DB'] ?? null;
        $request['projectStopReasons_DB'] = explode(',', $request['projectStopReasons_DB']);
        $roadProject->project_stop_reasons = ($request['projectStatus_DB'] == 1) ? $request['projectStopReasons_DB'] : null;
        $roadProject->can_release = $request['projectCanOpening'] ?? null;
        $roadProject->release_date = $request['projectOpeningDate_DB'] ?? null;
        $roadProject->supervisor_name = $request['projectNazerName_DB'] ?? null;
        $roadProject->responsible_name = $request['projectMasName_DB'] ?? null;
        $roadProject->report_date = $request['projectReportDate_DB'] ?? null;

        $roadConstruction = $request->user()->roadConstructionProjects()->save($roadProject);

        $file_index = 0;
        $files_path = [];
        while (true) {
            if ($request['item_files_' . $file_index]) {
                $files_path[$file_index]['path'] = $request->file('item_files_' . $file_index)
                    ->store('road_construction_projects');
                $file_index++;
            } else {
                break;
            }
        }

        if ($file_index > 0) {
            $roadConstruction->files()->createMany($files_path);
        }

        return response()->json([
            'status' => 'succeed',
            'message' => ''
        ], 201);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $roadProject = Auth::user()->roadConstructionProjects->find($id);
        
        if ($roadProject) {
            $roadProjectArray = [
                'id' => $roadProject->id,
                'operation_type' => $roadProject->operation_type,
                'operation_sub_types' => $roadProject->operation_sub_types,
                'start_cord' => [$roadProject->start_lat, $roadProject->start_lng],
                'end_cord' => [$roadProject->end_lat, $roadProject->end_lng],
                'project_distance' => $roadProject->project_distance,
                'province' => $roadProject->province,
                'city' => $roadProject->city,
                'credit_progress' => $roadProject->credit_progress,
                'physical_progress' => $roadProject->physical_progress
            ];
    
    
            return response()->json([
                'status' => 'succeed',
                'message' => '',
                'data' => $roadProjectArray
            ], 200);
        } else {
            return response()->json([
                'status' => 'error',
                'message' => 'Not found!',
                'data' => null
            ], 404);     
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $roadProject = Auth::user()->roadConstructionProjects->find($id);

        $roadProject->credit_progress = $request['credit_progress'];
        $roadProject->physical_progress = json_encode($request['physical_progress']);
    
        //$roadProject->save();
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $roadProject = Auth::user()->roadConstructionProjects->find($id);

        $roadProject->delete();
    }

    public function convertSerializeToJson() {
        $roadItems = RoadConstructionProject::all();

        /*foreach($roadItems as &$roadItem) {
            $roadItem->operation_sub_types = json_encode(unserialize($roadItem->operation_sub_types));
            $roadItem->physical_progress = json_encode(unserialize($roadItem->physical_progress));
            $roadItem->project_stop_reasons = json_encode(unserialize($roadItem->project_stop_reasons));
            $roadItem->save();
        }*/

        return response()->json([
            'status' => 'succeed',
            'message' => '',
            'data' => $roadItems
        ], 201);
    }
}
