<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\DailyPlanner;

class DailyPlannerController extends Controller
{
    // Menampilkan daftar planner
    public function index()
    {
        $planners = DailyPlanner::where('user_id', auth()->id())->get();
        return view('calendar.perencana', compact('planners'));
    }

    // Menyimpan planner baru
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'date' => 'required|date',
            'tasks' => 'required|array|min:1',
            'tasks.*' => 'string'
        ]);
    
        DailyPlanner::create([
            'user_id' => auth()->id(),
            'date' => $validatedData['date'],
            'tasks' => json_encode($validatedData['tasks']),
        ]);
    
        return redirect()->route('perencana-harian.index')->with('success', 'Planner berhasil dibuat.');
    }

    // Memperbarui planner
    public function update(Request $request, $id)
    {
        $validatedData = $request->validate([
            'date' => 'required|date',
            'tasks' => 'required|array|min:1',
            'tasks.*' => 'string'
        ]);
    
        dd($validatedData);
        $planner = DailyPlanner::findOrFail($id);
        $planner->update([
            'date' => $validatedData['date'],
            'tasks' => json_encode($validatedData['tasks'])
        ]);
    
        return redirect()->back()->with('success', 'Planner berhasil diperbarui.');
    }

    // Menghapus planner
    public function destroy($id)
    {
        $planner = DailyPlanner::findOrFail($id);
        $planner->delete();

        return redirect()->route('perencana-harian.index')->with('success', 'Planner berhasil dihapus.');
    }
}
