<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\NamazDiary;

class NamazDiaryController extends Controller
{
    public function index(Request $request)
    {
        return response()->json(
            NamazDiary::where('user_id', $request->user()->id)->get()
        );
    }

    public function store(Request $request)
    {
        $request->validate([
            'date' => 'required|date',
        ]);

        $exists = NamazDiary::where('user_id', $request->user()->id)
            ->where('date', $request->date)
            ->exists();

        if ($exists) {
            return response()->json([
                'message' => 'Diary already exists for this date'
            ], 400);
        }

        $diary = NamazDiary::create([
            'user_id' => $request->user()->id,
            'date' => $request->date,
            'fajr' => $request->fajr,
            'zuhar' => $request->zuhar,
            'asar' => $request->asar,
            'maghrib' => $request->maghrib,
            'isha' => $request->isha,
        ]);

        return response()->json($diary);
    }

    public function update(Request $request, $id)
    {
        $diary = NamazDiary::where('user_id', $request->user()->id)
            ->findOrFail($id);

        $diary->update($request->all());

        return response()->json([
            'message' => 'Updated'
        ]);
    }

    public function destroy(Request $request, $id)
    {
        $diary = NamazDiary::where('user_id', $request->user()->id)
            ->findOrFail($id);

        $diary->delete();

        return response()->json([
            'message' => 'Deleted'
        ]);
    }
}