<?php
session_start();
include '../../connection.php';
?>
<div class="card">
  <div class="card-header">
    <button class="btn btn-md btn-primary" data-toggle="modal" data-target="#create-complaint">
      <i class="fa fa-plus-circle"></i> Create Complaint
    </button>
  </div>
  <div class="card-body">
    <div class="table-responsive">
          <div id="my_complaint"></div>
    </div>

  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="create-complaint" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Create Complaint <i class="fa fa-book"></i></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      
      <form id="complaintForm" enctype="multipart/form-data">
        <div class="modal-body">

          <div class="mb-3">
            <label>Date Filed</label>
            <input type="text" class="form-control" value="<?= date('Y-m-d'); ?>" disabled>
          </div>

          <div class="mb-3">
            <label>Respondent</label>
            <input type="text" class="form-control" name="respondent" id="respondent">
          </div>

          <div class="mb-3">
            <label>Incident Address</label>
            <input type="text" class="form-control" name="incident_address" id="incident_address" placeholder="Enter incident location">
          </div>

          <div class="mb-3">
            <label>Complaint Type</label>
            <select class="form-control" id="complaint_types" name="complaint_type" required>
              <option value="">-- Select --</option>
              <?php
              $query = "SELECT * FROM `tbl_complaint_types`";
              $result = $conn->query($query);
              while ($row = $result->fetch_assoc()) {
                echo '<option value="' . htmlspecialchars($row['complaint_type_id']) . '">' . htmlspecialchars($row['complain_name']) . '</option>';
              }
              ?>
            </select>
          </div>

          <div class="mb-3">
            <label>Description</label>
            <textarea class="form-control" name="description" id="description" rows="3" placeholder="Describe the incident"></textarea>
          </div>

          <div class="mb-3">
            <label>Date of Incident</label>
            <input type="date" class="form-control" name="incident_date" id="incident_date">
          </div>

          <div class="mb-3">
            <label>Upload Evidence (Photo or Video)</label>
            <input type="file" class="form-control" name="evidence" id="evidence" accept="image/*,video/*">
          </div>

        </div>
      </form>

      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="saveComplaintBtn" onclick="add_complaints()">
          Save <i class="fa fa-save"></i>
        </button>
      </div>

    </div>
  </div>
</div>



<!-- Modal -->
<div class="modal fade" id="update-complaint" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Create Complaint <i class="fa fa-book"></i></h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      
      <div class="modal-body">

        <div class="mb-3">
          <label>Date Filed</label>
          <input type="text" class="form-control" value="<?= date('Y-m-d'); ?>" disabled>
        </div>

        <div class="mb-3">
          <label>Respondent</label>
          <input type="text" class="form-control" id="u_respondent">
        </div>

        <div class="mb-3">
          <label>Incident Address</label>
          <input type="hidden" id="res_id">
          <input type="hidden" id="u_complaint_types">
          <input type="text" class="form-control" id="u_incident_address" placeholder="Enter incident location">
        </div>

        <div class="mb-3">
          <label>Description</label>
          <textarea class="form-control" id="u_description" rows="3" placeholder="Describe the incident"></textarea>
        </div>

        <div class="mb-3">
          <label>Date of Incident</label>
          <input type="date" class="form-control" id="u_incident_date">
        </div>

      </div> <!-- END modal-body -->

      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary" id="saveComplaintBtn" onclick="update_complaint()">
          Save <i class="fa fa-save"></i>
        </button>
      </div>

    </div>
  </div>
</div>
<script>
  function update_complaint(){
     let UniqueID  = $('#res_id').val();
     let u_respondent = $('#u_respondent').val();
    let  u_incident_address =  $('#u_incident_address').val();
    let u_complaint_types  = $('#u_complaint_types').val();
     let u_description  = $('#u_description').val();
    let u_incident_date  = $('#u_incident_date').val();
    $.ajax({
      method: 'post',
      url: 'query/complaint_query.php',
      data:{
        "updating_complaints": 1,
        "UniqueID": UniqueID,
        "u_respondent": u_respondent,
        "u_incident_address": u_incident_address,
        "u_complaint_types": u_complaint_types,
        "u_description": u_description,
        "u_incident_date": u_incident_date
      },
      success: function(res){
       swal({
        title: "Success!",
        text: "Data updated successfully!",
        icon: "success",
      });

        load_complaint();
      }
    });
  }

  function edit_complaints(UniqueID,
    respondent,
incident_address,
complaint_type_id,
description,
incident_date){
    $('#res_id').val(UniqueID);
    $('#u_respondent').val(respondent);
     $('#u_incident_address').val(incident_address);
    $('#u_complaint_types').val(complaint_type_id);
     $('#u_description').val(description);
    $('#u_incident_date').val(incident_date);


  }

  function delete_complaints(UniqueID){
    swal({
  title: "Are you sure?",
  text: "Once deleted, you will not be able to recover this data file!",
  icon: "warning",
  buttons: true,
  dangerMode: true,
})
.then((willDelete) => {
  if (willDelete) {
     $.ajax({
      method: 'post',
      url: 'query/complaint_query.php',
      data:{
        "deleting_complaints": 1,
        "UniqueID": UniqueID
      },
      success: function(res){
        load_complaint();
      }
    });
    swal("Poof! Your data file has been deleted!", {
      icon: "success",
    });
  } else {
    swal("Your data file is safe!");
  }
});
   
  }

function add_complaints() {
    var formData = new FormData(document.getElementById("complaintForm"));
    formData.append("adding_complaints", 1);

    // Validation
    if (
        $('#incident_address').val() === "" ||
        $('#complaint_types').val() === "" ||
        $('#description').val() === "" ||
        $('#incident_date').val() === ""
    ) {
        swal("Oops!", "Please fill in all required fields!", "warning");
        return;
    }

    // Show progress bar (if not yet in HTML)
    if ($('#uploadProgressContainer').length === 0) {
        $('body').append(`
            <div id="uploadProgressContainer" style="
                position: fixed;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
                width: 350px;
                background: #fff;
                border: 1px solid #ccc;
                border-radius: 10px;
                padding: 20px;
                text-align: center;
                z-index: 9999;
                box-shadow: 0 0 10px rgba(0,0,0,0.2);
            ">
                <h6>Uploading your complaint...</h6>
                <div style="width: 100%; background: #eee; border-radius: 5px;">
                    <div id="uploadProgressBar" style="
                        width: 0%;
                        height: 15px;
                        background: #28a745;
                        border-radius: 5px;
                        transition: width 0.3s;
                    "></div>
                </div>
                <small id="uploadPercent">0%</small>
            </div>
        `);
    }

    $.ajax({
        method: 'POST',
        url: 'query/complaint_query.php',
        data: formData,
        processData: false, // required for file upload
        contentType: false, // required for file upload
        xhr: function(res) {
            alert(res)
            var xhr = new window.XMLHttpRequest();
            xhr.upload.addEventListener("progress", function(evt) {
                if (evt.lengthComputable) {
                    var percentComplete = Math.round((evt.loaded / evt.total) * 100);
                    $('#uploadProgressBar').css('width', percentComplete + '%');
                    $('#uploadPercent').text(percentComplete + '%');
                }
            }, false);
            return xhr;
        },
        beforeSend: function() {
            $('#uploadProgressContainer').fadeIn();
        },
        success: function(res) {
            alert(res)
            $('#uploadProgressContainer').fadeOut(function() {
                $(this).remove();
            });

            if (res.trim() === "success") {
                swal("Good job!", "Complaint added successfully!", "success");
                $('#create-complaint').modal('hide');
                $('#complaintForm')[0].reset();
                load_complaint();
            } else {
                swal("Error", res, "error");
            }
        },
        error: function(xhr, status, error) {
            $('#uploadProgressContainer').fadeOut(function() {
                $(this).remove();
            });
            swal("Error", "Something went wrong: " + error, "error");
        }
    });
}



$(document).ready(function() {
  $('.js-example-basic-single').select2({
    dropdownParent: $('#create-complaint'),
    theme: 'classic'
  });

  load_complaint();
});

function load_complaint(){
  $.ajax({
    method: 'POST',
    url: 'query/complaint_query.php',
    data: {
      "loading_complaints": 1
    },
    success: function(res){
      $('#my_complaint').html(res);
      $('#mytable').DataTable({ columnControl: ['order', 'searchDropdown'], ordering: { indicators: false, handler: false } });
    }
  });
}
</script>
