<?php
require_once('includes/load.php');
include_once('layouts/header.php');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Proses data form untuk menambah proyek
    $project_name = $db->escape($_POST['project_name']);
    $start_date = $db->escape($_POST['start_date']);
    $end_date = $db->escape($_POST['end_date']);
    $status = $db->escape($_POST['status']);
    
    // Validasi input (sesuaikan dengan kebutuhan)
    if (empty($project_name) || empty($start_date) || empty($end_date) || empty($status)) {
        $session->msg("d", "All fields are required.");
    } else {
        $query = "INSERT INTO project_timeline (project_name, start_date, end_date, status) VALUES ('{$project_name}', '{$start_date}', '{$end_date}', '{$status}')";
        if ($db->query($query)) {
            $session->msg("s", "Project added successfully.");
        } else {
            $session->msg("d", "Failed to add project.");
        }
    }
}

function get_project_timelines() {
    global $db;
    $query = "SELECT * FROM project_timeline ORDER BY start_date ASC";
    return $db->query($query);
}

$timelines = get_project_timelines();
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Project Timeline</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
  <link rel="stylesheet" href="libs/css/main.css" />
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.24/css/jquery.dataTables.min.css" />
  <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> -->
  <script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.anychart.com/releases/8.10.0/js/anychart-bundle.min.js"></script>
</head>

<body>
  <?php if ($session->isUserLoggedIn(true)): ?>
  <div class="container">
    <h1 class="text-center">Project Timeline</h1>

    <!-- Form to input projects like a spreadsheet -->
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">Add Projects</h3>
      </div>
      <div class="panel-body">
        <table id="project-input-table" class="table table-bordered">
          <thead>
            <tr>
              <th>Project Name</th>
              <th>Start Date</th>
              <th>End Date</th>
              <th>Status</th>
              <th>Action</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td><input type="text" class="form-control" name="project_name[]"></td>
              <td><input type="date" class="form-control" name="start_date[]"></td>
              <td><input type="date" class="form-control" name="end_date[]"></td>
              <td>
                <select class="form-control" name="status[]">
                  <option value="Not Started">Not Started</option>
                  <option value="In Progress">In Progress</option>
                  <option value="Completed">Completed</option>
                </select>
              </td>
              <td><button class="btn btn-success add-row">Add Row</button></td>
            </tr>
          </tbody>
        </table>
        <button id="submit-projects" class="btn btn-primary">Submit Projects</button>
      </div>
    </div>

    <!-- DataTable for project timelines -->
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">Project List</h3>
      </div>
      <div class="panel-body">
        <table id="project-table" class="display">
          <thead>
            <tr>
              <th>Project Name</th>
              <th>Start Date</th>
              <th>End Date</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($timelines as $timeline): ?>
            <tr>
              <td><?php echo htmlspecialchars($timeline['project_name']); ?></td>
              <td><?php echo $timeline['start_date']; ?></td>
              <td><?php echo $timeline['end_date']; ?></td>
              <td><?php echo htmlspecialchars($timeline['status']); ?></td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>

    <!-- Gantt Chart Display -->
    <div id="container" style="width: 100%; height: 500px;"></div>

    <script>
    $(document).ready(function() {
      $('#project-table').DataTable();

      $('.add-row').click(function() {
        var newRow = `<tr>
                        <td><input type="text" class="form-control" name="project_name[]"></td>
                        <td><input type="date" class="form-control" name="start_date[]"></td>
                        <td><input type="date" class="form-control" name="end_date[]"></td>
                        <td>
                            <select class="form-control" name="status[]">
                                <option value="Not Started">Not Started</option>
                                <option value="In Progress">In Progress</option>
                                <option value="Completed">Completed</option>
                            </select>
                        </td>
                        <td><button class="btn btn-danger remove-row">Remove</button></td>
                    </tr>`;
        $('#project-input-table tbody').append(newRow);
      });

      $(document).on('click', '.remove-row', function() {
        $(this).closest('tr').remove();
      });

      $('#submit-projects').click(function() {
        var formData = $('#project-input-table').find('input, select').serialize();
        $.post('project_timeline.php', formData, function(response) {
          // Handle response from the server if needed
          location.reload(); // Reload page to reflect new data
        });
      });
    });

    anychart.onDocumentReady(function() {
      var data = [
        <?php foreach ($timelines as $timeline): ?> {
          id: <?php echo $timeline['id']; ?>,
          name: "<?php echo htmlspecialchars($timeline['project_name']); ?>",
          from: "<?php echo $timeline['start_date']; ?>",
          to: "<?php echo $timeline['end_date']; ?>",
          progress: <?php echo $timeline['status'] == 'Completed' ? 100 : ($timeline['status'] == 'In Progress' ? 50 : 0); ?>
        },
        <?php endforeach; ?>
      ];

      var chart = anychart.ganttProject();
      chart.data(data);
      chart.container('container');
      chart.draw();
    });
    </script>
  </div>
  <?php endif; ?>

  <!-- JavaScript includes -->
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
</body>

</html>