<?php
require('header.php');
?>


<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
  <!-- Content Header (Page header) -->
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <!-- <h1>Calendar</h1> -->
        </div>
        <div class="col-sm-6">
          <!-- <ol class="breadcrumb float-sm-right">
              <li class="breadcrumb-item"><a href="#">Home</a></li>
              <li class="breadcrumb-item active">Calendar</li>
            </ol> -->
        </div>
      </div>
    </div><!-- /.container-fluid -->
  </section>

  <!-- Main content -->
  <section class="content">
    <div class="container-fluid">
      <div class="row">

        <div class="col-md-12">
          <!-- general form elements -->
          <div class="card card-secondary">
            <div class="card-header" style="background-color: black;">
              <h3 class="card-title">Add Event</h3>
              <ol class="breadcrumb float-sm-right" style="background-color: black;">
                <li class="breadcrumb-item"><a href="#">Home</a></li>
                <li class="breadcrumb-item active">Calendar</li>
              </ol>
            </div>
            <!-- /.card-header -->
            <!-- form start -->

            <div class="card-body Ecalendar">
              <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
              <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.0/main.min.css">
              <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
              <style>
                .Ecalendar :root {
                  --bs-success-rgb: 71, 222, 152 !important;
                }



                /* .Ecalendar  .btn-info.text-light:hover,
                  .btn-info.text-light:focus {
                    background: #000;
                  } */

                .Ecalendar .row {
                  background-color: #e6e7e8;

                  box-shadow: 0 0 40px 0 #9ba1a7;

                  padding: 2%;
                }

                .Ecalendar a {
                  text-decoration: none;
                }

                .Ecalendar table,
                tbody,
                td,
                tfoot,
                th,
                thead,
                tr {
                  border-color: #c2c2c2 !important;
                  border-style: solid;
                  border-width: 1px !important;
                }
              </style>


              <?php if (isset($_GET['error'])) { ?>
                <div class="alert alert-denger  col-12">
                  <p class="error"><?php echo $_GET['error']; ?></p>
                </div>



              <?php } ?>
              <?php if (isset($_GET['success'])) { ?>
                <div class="alert alert-success  col-12">
                  <p class="success"><?php echo $_GET['success']; ?></p>
                </div>


              <?php } ?>
              <?php
              require_once('connection.php');

              $schedules = $conn->query("SELECT * FROM `calendar_event_master`");
              $sched_res = [];

              foreach ($schedules->fetch_all(MYSQLI_ASSOC) as $row) {
                $row['sdate'] = date("F d, Y h:i A", strtotime($row['start_datetime']));
                $row['edate'] = date("F d, Y h:i A", strtotime($row['end_datetime']));
                $sched_res[$row['id']] = $row;
              }

              if (isset($conn)) $conn->close();
              ?>


              <div class="container py-5" id="page-container">
                <div class="row">
                  <div class="col-md-9">
                    <div id="calendar"></div>
                  </div>
                  <div class="col-md-3">
                    <div class="cardt rounded-0 shadow">
                      <div class="card-header bg-gradient bg-primary text-light">
                        <h5 class="card-title">Schedule Form</h5>
                      </div>
                      <div class="card-body">
                        <div class="container-fluid">
                          <form action="save_schedule.php" method="post" id="schedule-form">
                            <input type="hidden" name="id" value="">
                            <div class="form-group mb-2">
                              <label for="title" class="control-label">Title</label>
                              <input type="text" class="form-control form-control-sm rounded-0" name="title" id="title" required>
                            </div>
                            <div class="form-group mb-2">
                              <label for="description" class="control-label">Description</label>
                              <textarea rows="3" class="form-control form-control-sm rounded-0" name="description" id="description" required></textarea>
                            </div>
                            <div class="form-group mb-2">
                              <label for="start_datetime" class="control-label">Start</label>
                              <input type="datetime-local" class="form-control form-control-sm rounded-0" name="start_datetime" id="start_datetime" required>
                            </div>
                            <div class="form-group mb-2">
                              <label for="end_datetime" class="control-label">End</label>
                              <input type="datetime-local" class="form-control form-control-sm rounded-0" name="end_datetime" id="end_datetime" required>
                            </div>
                          </form>
                        </div>
                      </div>
                      <div class="card-footer">
                        <div class="text-center">
                          <button class="btn btn-primary btn-sm rounded-0" type="submit" form="schedule-form"><i class="fa fa-save"></i> Save</button>
                          <button class="btn btn-default border btn-sm rounded-0" type="reset" form="schedule-form"><i class="fa fa-reset"></i> Cancel</button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <!-- Event Details Modal -->
              <div class="modal fade" tabindex="-1" data-bs-backdrop="static" id="event-details-modal">
                <div class="modal-dialog modal-dialog-centered">
                  <div class="modal-content rounded-0">
                    <div class="modal-header rounded-0">
                      <h5 class="modal-title">Schedule Details</h5>
                      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    </div>
                    <div class="modal-body rounded-0">
                      <div class="container-fluid">
                        <dl>
                          <dt class="text-muted">Title</dt>
                          <dd id="title" class="fw-bold fs-4"></dd>
                          <dt class="text-muted">Description</dt>
                          <dd id="description" class=""></dd>
                          <dt class="text-muted">Start</dt>
                          <dd id="start" class=""></dd>
                          <dt class="text-muted">End</dt>
                          <dd id="end" class=""></dd>
                        </dl>
                      </div>
                    </div>
                    <div class="modal-footer rounded-0">
                      <div class="text-end">
                        <button type="button" class="btn btn-dark btn-sm rounded-0" id="edit" data-id="">Edit</button>
                        <button type="button" class="btn btn-dark btn-sm rounded-0" id="delete" data-id="">Delete</button>
                        <button type="button" class="btn btn-dark btn-sm rounded-0" data-dismiss="modal">Close</button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>




            </div>
          </div>
        </div>
      </div>
      <!-- /.row -->
    </div>
    <!-- /.container-fluid -->
  </section>
  <!-- /.content -->
</div>
<!-- /.content-wrapper -->

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> -->
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.11.0/main.min.js"></script>
<script src="script.js"></script>
<script>
  var scheds = $.parseJSON('<?= json_encode($sched_res) ?>')
</script>
<script>
  var calendar;
  var Calendar = FullCalendar.Calendar;
  var events = [];

  $(function() {

    if (!!scheds) {
      Object.keys(scheds).map(k => {
        var row = scheds[k]
        events.push({
          id: row.id,
          title: row.title,
          start: row.start_datetime,
          end: row.end_datetime
        });
      });
    }

    var date = new Date()
    var d = date.getDate(),
      m = date.getMonth(),
      y = date.getFullYear(),

      calendar = new Calendar(document.getElementById('calendar'), {
        headerToolbar: {
          left: 'prev,next today',
          right: 'dayGridMonth,dayGridWeek,list',
          center: 'title',
        },
        selectable: true,
        themeSystem: 'bootstrap',
        events: events,
        eventClick: function(info) {
          var details = $('#event-details-modal');
          var id = info.event.id;

          if (!!scheds[id]) {
            details.find('#title').text(scheds[id].title);
            details.find('#description').text(scheds[id].description);
            details.find('#start').text(scheds[id].sdate);
            details.find('#end').text(scheds[id].edate);
            details.find('#edit,#delete').attr('data-id', id);
            details.modal('show');
          } else {
            alert("Event is undefined");
          }
        },
        eventDidMount: function(info) {
          // Do Something after events mounted
        },
        editable: true
      });

    calendar.render();

    // Form reset listener
    $('#schedule-form').on('reset', function() {
      $(this).find('input:hidden').val('');
      $(this).find('input:visible').first().focus();
    });

    // Edit Button
    $('#edit').click(function() {
      var id = $(this).attr('data-id');

      if (!!scheds[id]) {
        var form = $('#schedule-form');

        console.log(String(scheds[id].start_datetime), String(scheds[id].start_datetime).replace(" ", "\\t"));
        form.find('[name="id"]').val(id);
        form.find('[name="title"]').val(scheds[id].title);
        form.find('[name="description"]').val(scheds[id].description);
        form.find('[name="start_datetime"]').val(String(scheds[id].start_datetime).replace(" ", "T"));
        form.find('[name="end_datetime"]').val(String(scheds[id].end_datetime).replace(" ", "T"));
        $('#event-details-modal').modal('hide');
        form.find('[name="title"]').focus();
      } else {
        alert("Event is undefined");
      }
    });

    // Delete Button / Deleting an Event
    $('#delete').click(function() {
      var id = $(this).attr('data-id');

      if (!!scheds[id]) {
        var _conf = confirm("Are you sure to delete this scheduled event?");
        if (_conf === true) {
          location.href = "./delete_schedule.php?id=" + id;
        }
      } else {
        alert("Event is undefined");
      }
    });
  });
</script>

<?php
require("footer.php")
?>