@extends('layouts.main')
@section('title', 'Calendar Planner')
@section('content')
<div class="content-body">
  <div class="container-fluid">
    <div class="row page-titles">
      <ol class="breadcrumb">
        <li class="breadcrumb-item active"><a href="javascript:void(0)">Home</a></li>
        <li class="breadcrumb-item"><a href="javascript:void(0)">Calendar Planner</a></li>
      </ol>
    </div>
    <!-- row -->
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-header">
            <h4 class="card-title">Calendar Planner</h4>
            <button type="button" class="btn btn-primary float-right" data-bs-toggle="modal" data-bs-target="#addPlannerModal">
              <i class="fa fa-plus"></i>
            </button>
          </div>
          <div class="card-body">
            <div class="table-responsive">
              <table id="example2" class="display" style="min-width: 845px">
                <thead>
                  <tr>
                    <th>ID</th>
                    <th>Date</th>
                    <th>Tasks</th>
                    <th>Aksi</th>
                  </tr>
                </thead>
                <tbody>
                  @foreach ($planners as $planner)
                    <tr>
                      <td>{{ $loop->iteration }}</td>
                      <td>{{ $planner->date }}</td>
                      <td>
                        <ul>
                          @foreach (json_decode($planner->tasks) as $task)
                            <li>{{ $task }}</li>
                          @endforeach
                        </ul>
                      </td>
                      <td>
                        <button type="button" class="btn btn-warning" data-bs-toggle="modal" data-bs-target="#editPlannerModalCenter{{ $planner->id }}">
                          <i class="fa fa-edit"></i>
                        </button>
                        <button type="button" class="btn btn-danger" onclick="confirmDelete({{ $planner->id }})">
                          <i class="fa fa-trash"></i>
                        </button>
                        <form id="delete-form-{{ $planner->id }}" action="{{ route('perencana-harian.destroy', $planner->id) }}" method="POST" style="display: none;">
                          @csrf
                          @method('DELETE')
                        </form>
                      </td>
                    </tr>

<!-- Edit Planner Modal -->
<div class="modal fade" id="editPlannerModalCenter{{ $planner->id }}" tabindex="-1" role="dialog" aria-labelledby="editPlannerModalCenterLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="editPlannerModalCenterLabel">Edit Planner</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="{{ route('perencana-harian.update', $planner->id) }}" method="POST" onsubmit="handleFormSubmit(event, 'edit-submit-{{ $planner->id }}')">
                @csrf
                @method('PUT')
                <div class="modal-body">
                    <div class="form-group">
                        <label for="date">Date:</label>
                        <input type="date" name="date" class="form-control" value="{{ $planner->date }}" required>
                    </div>
                    <div class="form-group" id="task-container-{{ $planner->id }}">
                        <label for="tasks">Tasks:</label>
                        @php
                            $tasks = json_decode($planner->tasks, true) ?? [];
                        @endphp
                        @foreach ($tasks as $task)
                            <div class="task-input-group mb-2">
                                <input type="text" name="tasks[]" class="form-control" value="{{ $task }}" required>
                                <button type="button" class="btn btn-danger remove-task" onclick="removeTaskInput('task-container-{{ $planner->id }}', this)">Hapus</button>
                            </div>
                        @endforeach
                    </div>
                    <button type="button" class="btn btn-primary" onclick="addTaskInput('task-container-{{ $planner->id }}')">Tambah Task</button>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                    <button type="submit" id="edit-submit-{{ $planner->id }}" class="btn btn-success">Update</button>
                </div>
            </form>
        </div>
    </div>
</div>



                  @endforeach
                </tbody>
              </table>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

<!-- Add Planner Modal -->
<div class="modal fade" id="addPlannerModal" tabindex="-1" role="dialog" aria-labelledby="addPlannerModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addPlannerModalLabel">Tambah Planner</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form action="{{ route('perencana-harian.store') }}" method="POST" onsubmit="handleFormSubmit(event, 'add-submit')">
        @csrf
        <div class="modal-body">
          <div class="form-group">
            <label for="date">Date:</label>
            <input type="date" name="date" class="form-control" required>
          </div>
          <div class="form-group" id="task-container">
            <label for="tasks">Tasks:</label>
            <div class="task-input-group mb-2">
              <input type="text" name="tasks[]" class="form-control" placeholder="Task" required>
              <button type="button" class="btn btn-danger" onclick="removeTaskInput('task-container', this)">Hapus</button>
            </div>
          </div>
          <button type="button" class="btn btn-primary" onclick="addTaskInput('task-container')">Tambah Task</button>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
          <button type="submit" id="add-submit" class="btn btn-success">Simpan</button>
        </div>
      </form>
    </div>
  </div>
</div>
@endsection

@section('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Fungsi untuk update data di tabel setelah edit
    function updatePlannerRow(plannerId, date, tasks) {
        let row = document.querySelector(`#planner-row-${plannerId}`);
        if (row) {
            row.querySelector('.planner-date').innerText = date;
            let taskList = row.querySelector('.planner-tasks');
            taskList.innerHTML = ''; // Hapus task lama
            tasks.forEach(task => {
                let li = document.createElement('li');
                li.innerText = task;
                taskList.appendChild(li);
            });
        }
    }

    // Fungsi handle submit edit tanpa reload
    document.querySelectorAll('.edit-planner-form').forEach(form => {
        form.addEventListener('submit', function(event) {
            event.preventDefault();
            let formData = new FormData(this);
            let plannerId = this.getAttribute('data-planner-id');

            fetch(this.action, {
                method: 'POST',
                body: formData
            }).then(response => response.json())
              .then(data => {
                if (data.success) {
                    let updatedTasks = JSON.parse(data.planner.tasks);
                    updatePlannerRow(plannerId, data.planner.date, updatedTasks);
                    document.querySelector(`#editPlannerModalCenter${plannerId} .btn-close`).click(); // Tutup modal
                } else {
                    alert('Gagal memperbarui data');
                }
            }).catch(error => console.log(error));
        });
    });
});


// Fungsi untuk konfirmasi hapus
function confirmDelete(plannerId) {
    Swal.fire({
        title: 'Apakah kamu yakin?',
        text: "Anda tidak akan dapat mengembalikan ini!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Ya, hapus!'
    }).then((result) => {
        if (result.isConfirmed) {
            document.getElementById('delete-form-' + plannerId).submit();
        }
    });
}

// Fungsi untuk handle form submit
function handleFormSubmit(event, buttonId) {
    event.preventDefault();
    const button = document.getElementById(buttonId);
    button.disabled = true;
    button.innerHTML = 'Loading...';
    event.target.submit();
}
</script>
@endsection
