<?php

namespace App\Http\Controllers;

use App\Http\Resources\PeriodicActivityResource;
use App\Models\periodic_activity;
use App\Models\station;
use App\Models\locations;
use Carbon\Carbon;
use Illuminate\Http\Request;

class PeriodicActivityController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index( Request $request)
    {
        $data= [];
        if ($request->type =="today") {
            $data= PeriodicActivityResource::collection(periodic_activity::whereDate("created_at",Carbon::today())->get());

        }
        return response()->json(// todo : see macro vidoes
            [
                "data" => $data,
                "message" => "success",
                "status" => true,
            ]
        );
    }

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

    public function delete(Request $request, $id)
    {
        $activity = periodic_activity::find($id);
       try {
            $activity->delete();
            return response()->json([
                "data" => $activity,
                "message" => "success",
                "status" => true,
            ]);
        } catch (Exception $e) {
            return response()->json([
                "message" => "An error occurred",
                "error" => $e->getMessage(),
                "status" => false,
            ], 500);
        }
    }
    
    public function store(Request $request)
    {
        try {
            $request->validate([
                'activity_no' => 'required',
                'activity_name' => 'required',
                'period' => 'required',
                'period_category' => 'required',
                'last_date' => 'required|date',
                'next_date' => 'required|date',
                'station_id' => 'required',
                'description' => 'nullable|string',
            ], [
                'activity_no.required' => 'Activity number is required',
                'activity_no.unique' => 'Acitivity number must be unique, this one has been taken',
                'activity_name.required' => 'Acitivity name is required',
                'activity_name.unique' => 'Acitivity name must be unique, this one has been taken',
                'period.required' => 'Activity must have a period number',
                'period_category.required' => 'Acitivity must have a period type to calculate the next day date',
                'last_date.required' => 'Last Done date is not set',
                'last_date.date' => 'Last Done type must be Date',
                'next_date.required' => 'Something went wrong in calcualting next day for this activity',
                'next_date.date' => 'Next Date type must be Date',
                'station_id.required' => 'Please select a station',
            ]);
            $activity = new periodic_activity();
            $activity->activity_no = $request->activity_no;
            $activity->activity_name = $request->activity_name;
            $activity->period = $request->period;
            $activity->period_category = $request->period_category;
            $activity->last_date = $request->last_date;
            $activity->next_date = $request->next_date;
            $activity->station_id = $request->station_id;
            $activity->description = $request->description;
            $activity->save();
    
            return response()->json([
                "data" => $activity,
                "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(periodic_activity $periodic_activity, Request $request)
        {
            $data= [];
            if ($request->type =="today") {
                $data= (periodic_activity::where("created_at",Carbon::today())->toSql());
                
            }else{
             $stationIds=locations::find($request->companyid)->stations()->pluck('id');
             $data=periodic_activity::whereIn('station_id',$stationIds)->with('station')->get();
             
            }
            return response()->json(// todo : see macro vidoes
                [
                    "data" => $data,
                    "message" => "success",
                    "status" => true,
                ]
            );
        }
        
        
        public function find(periodic_activity $periodic_activity, Request $request, $id)
        {
            // $data = periodic_activity::find($id)->with('station');
            $data = periodic_activity::where('id', $id)->with('station')->get();
            return response()->json(// todo : see macro vidoes
                [
                    "data" => $data,
                    "message" => "success",
                    "status" => true,
                ]
            );
        }

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

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, periodic_activity $periodic_activity , $id)
    {
     try {
            $request->validate([
                'activity_no' => 'required',
                'activity_name' => 'required',
                'period' => 'required',
                'period_category' => 'required',
                'last_date' => 'required|date',
                'next_date' => 'required|date',
                'station_id' => 'required',
                'description' => 'nullable|string',
            ], [
                'activity_no.required' => 'Activity number is required',
                'activity_no.unique' => 'Acitivity number must be unique, this one has been taken',
                'activity_name.required' => 'Acitivity name is required',
                'activity_name.unique' => 'Acitivity name must be unique, this one has been taken',
                'period.required' => 'Activity must have a period number',
                'period_category.required' => 'Acitivity must have a period type to calculate the next day date',
                'last_date.required' => 'Last Done date is not set',
                'last_date.date' => 'Last Done type must be Date',
                'next_date.required' => 'Something went wrong in calcualting next day for this activity',
                'next_date.date' => 'Next Date type must be Date',
                'station_id.required' => 'Please select a station',
            ]);
            $activity = periodic_activity::find($id);
            $activity->activity_no = $request->activity_no;
            $activity->activity_name = $request->activity_name;
            $activity->period = $request->period;
            $activity->period_category = $request->period_category;
            $activity->last_date = $request->last_date;
            $activity->next_date = $request->next_date;
            $activity->station_id = $request->station_id;
            $activity->description = $request->description;
            $activity->save();
    
            return response()->json([
                "data" => $activity,
                "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);
            }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(periodic_activity $periodic_activity)
    {
        //
    }
    public function search(Request $request)
    {
        // return $request;
        // $locations = $request->input("location_search");
      $activity = periodic_activity::when($request->input("activity_name"), fn($query) => $query
            ->where("activity_name", $request->input("activity_name")))
            ->when($request->input("activity_number"), fn($query) => $query
                ->where("activity_no", $request->input("activity_number")))
            ->when($request->input("station_search"), fn($query) => $query
                ->whereIn("station_id", $request->input("station_search")))
            ->when($request->input("start_date"), fn($query) => $query
                ->where("next_date", "<=", $request->input("start_date")))
            // ->when($request->input("end_date"), fn($query) => $query
            //     ->where("next_date", "<=", $request->input("end_date")))
            ->when(
                $request->input("location_search"),fn($query) => $query
                ->join('stations', 'periodic_activities.station_id', '=', 'stations.id')
                ->where(function($query) use ($request) {
                    $array = $request->input("location_search", []);
                    foreach ($array as $item) {
                         $query->orWhere('stations.station_no', 'LIKE', $item . '%');
                    }
                })
            )->with("station")->get();

            return response()->json([
                "data" => $activity,
                "message" => "success",
                "status" => true,
            ]);

    }
     public function findStations(Request $request)
    {
        return ($request->location_search);
        $stations = station :: when($request->input("location_search"), fn($query) => $query 
        ->whereIn("parent_id", $request->input("location_search")) )->with("station")->get();
    }
    public function byStationId (Request $request)
    {
      $activity = periodic_activity::whereIn('station_id', $request->ids)->get();
        return response()->json(
            [
                "data" => $activity,
                "message" => "success",
                "status" => true,
            ]
        );
    }
    public function stationActivities(Request $request, $id)
    {
        $data = periodic_activity::where('station_id', $id)->with("station")->get();
        return response()->json(
            [
                "data" => $data,
                "message" => "success",
                "status" => true,
            ]
        );
    }
    public function toDoActivity(Request $request) {
        $data = periodic_activity::join('stations', 'periodic_activities.station_id', '=', 'stations.id')
            ->where('next_date', '<=', Carbon::today());
        if ($locationSearch = $request->input("location_search")) {
            $data->where(function ($query) use ($locationSearch) {
                foreach ((array) $locationSearch as $item) {
                    $query->orWhere('stations.station_no', 'LIKE', "{$item}%");
                }
            });
        }
        if ($stations = $request->input("station_search")) {
            $data->where(function ($query) use ($stations) {
                foreach ((array) $stations as $station) {
                    $query->orWhere('stations.id', $station);
                }
            });
        }

        return response()->json([
            "data" => $data->get(),
            "message" => "success",
            "status" => true,
        ]);
    }
    
}
