<?php

namespace App\Http\Controllers;

use App\Http\Resources\StationResource;
use App\Models\station;
use Illuminate\Http\Request;
use App\Traits\FileUploader;
use Carbon\Carbon;

class StationController extends Controller
{
    use FileUploader;
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        return StationResource::collection(station::orderBy('station_no')->get());
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    { 
        try{
        $request->validate([
            'station_number' => 'required|max:40',
            'station_name' => 'required|max:40',
            'station_code' => 'required|max:40',
            'parent' => 'nullable|integer',
            'machine_type' => 'nullable|string|max:40',
            'manufactured_date' => 'nullable|integer|between:1900,2100',
            'manufacturer_named' => 'nullable|string|max:40',
            'serial_number' => 'nullable|string|max:40',
            'status' => 'nullable',
            'priority' => 'nullable|integer',
            'description' => 'nullable|string|max:1000',
            'pic' => 'nullable|image|mimes:jpeg,png,jpg,gif',
        ], [
            'station_number.required' => 'Station number is required.',
            'station_name.required' => 'Station name is required.',
            'station_code.required' => 'Station code is required.',
            'parent.integer' => 'Parent ID must be an integer.',
            'manufactured_date.integer' => 'Manufactured date must be an integer.',
            'manufactured_date.between' => 'Manufactured date must be between 1900 and 2100.',
            'serial_number.string' => 'Serial number must be a string.',
            'priority.integer' => 'Priority must be an integer.',
            'description.string' => 'Description must be a string.',
            'pic.image' => 'Uploaded file must be an image.',
            'pic.mimes' => 'Image must be a file of type: jpeg, png, jpg, gif.',
        ]);
        $station = new station();
        if (!empty($request->pic)) {
            $station->pic = $this->UploadFile("pic", $request, "stations", "assets/uploaded/stations/")["path"];
        }
        $station->station_no = $request->station_number;
        $station->station_name = $request->station_name;
        $station->station_code = $request->station_code;
        $station->parent_id = $request->parent;
        $station->machine_type = $request->machine_type;
        $station->manufactured_date = $request->manufactured_date;
        $station->manufacturer_named = $request->manufacturer_named;
        $station->serial_number = $request->serial_number;
        $station->status = $request->status;
        $station->priority = $request->priority;
        $station->description = $request->description;

        $station->save();
        return response()->json(
            [
                "data" => $station,
                "message" => "success",
                "status" => true,
            ], 201);
            
        }catch (IlluminateValidationValidationException $e) {
        return response()->json([
            "d" => "Validation Error",
            "errors" => $e->validator->errors(),
            "status" => false,
        ], 422);

    } catch (Exception $e) {
            return response()->json([
                "message" => "An error occurred",
                "error" => $e->getMessage(),
                "status" => false,
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(station $station, $id)
    {
        return response()->json(// todo : see macro vidoes
            [
                "data" => new StationResource(station::find($id)),
                "message" => "success",
                "status" => true,
            ]
        );
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(station $station)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, $id)
    {
        try{
        $request->validate([
            'station_number' => 'required|max:40',
            'station_name' => 'required|max:40',
            'station_code' => 'required|max:40',
            'parent' => 'nullable|integer',
            'machine_type' => 'nullable|string|max:40',
            'manufactured_date' => 'nullable|integer|between:1900,2100',
            'manufacturer_named' => 'nullable|string|max:40',
            'serial_number' => 'nullable|string|max:40',
            'status' => 'nullable',
            'priority' => 'nullable|integer',
            'description' => 'nullable|string|max:1000',
            'pic' => 'nullable|image|mimes:jpeg,png,jpg,gif',
        ], [
            'station_number.required' => 'Station number is required.',
            'station_name.required' => 'Station name is required.',
            'station_code.required' => 'Station code is required.',
            'parent.integer' => 'Parent ID must be an integer.',
            'manufactured_date.integer' => 'Manufactured date must be an integer.',
            'manufactured_date.between' => 'Manufactured date must be between 1900 and 2100.',
            'serial_number.string' => 'Serial number must be a string.',
            'priority.integer' => 'Priority must be an integer.',
            'description.string' => 'Description must be a string.',
            'pic.image' => 'Uploaded file must be an image.',
            'pic.mimes' => 'Image must be a file of type: jpeg, png, jpg, gif.',
        ]);
        $station = station::find($id);
         if($request->deleted_picture && $request->deleted_picture=="true"){
            $station->pic = null;
        }
        if (!empty($request->pic)) {
            $station->pic = $this->UploadFile("pic", $request, "stations", "assets/uploaded/stations/")["path"];
        }
        $date = Carbon::createFromDate($request->manufactured_date, 1, 1); 
        $station->description = $request->description;
        $station->station_name = $request->station_name;
        $station->station_no = $request->station_number;
        $station->parent_id = $request->parent;
        $station->machine_type = $request->machine_type;
        $station->manufactured_date = $date;
        $station->manufacturer_named = $request->manufacturer_named;
        $station->serial_number = $request->serial_number;
        $station->priority = $request->priority;
        $station->station_code = $request->station_code;
        $station->save();
        return response()->json(// todo : see macro vidoes
            [
                "data" => new StationResource(station::find($id)),
                "message" => "success",
                "status" => true,
            ], 201);
        }catch (IlluminateValidationValidationException $e) {
        return response()->json([
            "d" => "Validation Error",
            "errors" => $e->validator->errors(),
            "status" => false,
        ], 422);

    } catch (Exception $e) {
            return response()->json([
                "message" => "An error occurred",
                "error" => $e->getMessage(),
                "status" => false,
            ], 500);
        }
    }

   
    public function searchStations(Request $request){
        // return $request;
        $data = station::whereIn('parent_id', $request->ids)->get();
        return response()->json(
            [
                "data" => $data,
                "message" => "success",
                "status" => true,
            ]
        );
    }
    public function getStationsByParents(Request $request, $parent_id = 0)
    {
       $station = station::where("parent_id", $parent_id)->get();
        $resuslt = StationResource::collection($station);
        return response()->json(// todo : see macro vidoes
            [
                "data" => $resuslt->sortby('station_number'),
                "message" => "success",
                "status" => true,
            ]
        );
    }
}
