<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>The Fraternal Order of Eagles</title>
  <!-- Bootstrap CSS -->
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
  <!-- DataTables CSS -->
  <link href="https://cdn.datatables.net/1.10.24/css/dataTables.bootstrap4.min.css" rel="stylesheet">
  <link href="https://cdn.datatables.net/responsive/2.2.9/css/responsive.bootstrap4.min.css" rel="stylesheet">
  <!-- jQuery -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <!-- DataTables JS -->
  <script src="https://cdn.datatables.net/1.10.24/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.24/js/dataTables.bootstrap4.min.js"></script>
  <script src="https://cdn.datatables.net/responsive/2.2.9/js/dataTables.responsive.min.js"></script>
  <script src="https://cdn.datatables.net/responsive/2.2.9/js/responsive.bootstrap4.min.js"></script>
  <style>
    /* Custom CSS for search bar */
    body {
      background-image: url('https://source.unsplash.com/random/1920x1080'); /* Add your background image URL */
      background-size: cover;
      background-repeat: no-repeat;
      background-attachment: fixed;
      background-position: center;
      color: rgba(255, 255, 255, 0.9); /* Text color with some transparency */
    }
    .dataTables_wrapper {
      color: #333; /* DataTable text color */
      background-color: rgba(255, 255, 255, 0.9); /* DataTable background color with some transparency */
      border-radius: 8px; /* Rounded corners for DataTable */
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.3); /* Add shadow for DataTable */
    }
    .dataTables_wrapper .dataTables_paginate .paginate_button {
      color: #007bff; /* Pagination button text color */
    }
    .dataTables_wrapper .dataTables_paginate .paginate_button.current {
      color: #fff; /* Current page button text color */
      background-color: #007bff; /* Current page button background color */
    }
    .table {
      width: 100%; /* Make the table occupy the whole width */
    }
    .additional-fields {
      display: none; /* Hide additional fields by default */
    }
    .modal-body label {
      color: #000 !important; /* Set color to black */
    }
    /* Hide location column on smaller screens */
    @media (max-width: 575.98px) {
      .hide-location th:nth-child(2),
      .hide-location td:nth-child(2) {
        display: none;
      }
    }
  </style>
</head>
<body>

<div class="container">
  <div class="row justify-content-center">
    <div class="col-md-8">
      <div class="text-center">
        <h1>The Fraternal Order of Eagles</h1>
        <p>Find what you're looking for!</p>
      </div>
      <form class="search-bar" id="searchForm" type="get">
        <div class="input-group mb-3">
          <input type="text" name="search" class="form-control" placeholder="Search for...">
          <div class="input-group-append">
            <button class="btn btn-primary" type="button" id="toggleFieldsBtn">Additional Filters</button>
          </div>
        </div>
        <div class="additional-fields">
          <div class="form-row">
            <div class="col-md-6 mb-3">
              <label for="location" style="color: rgba(255, 255, 255, 0.9);">Location</label>
              <input type="text" class="form-control" id="location" name="location" placeholder="Enter location">
            </div>
            <div class="col-md-6 mb-3">
              <label for="category" style="color: rgba(255, 255, 255, 0.9);">Category</label>
              <select class="form-control" id="category" name="category">
                <option value="">Choose category...</option>
                <option value="Electronics">Electronics</option>
                <option value="Clothing">Clothing</option>
                <option value="Books">Books</option>
                <!-- Add more options as needed -->
              </select>
            </div>
          </div>
        </div>
        <button class="btn btn-primary" type="submit">Search</button>
      </form>
    </div>
  </div>
</div>

<div class="container mt-5 col-md-12">
  <div class="row">
    <div class="col-md-12">
      <table class="table table-bordered hide-location" width="100%" id="dataTable" cellspacing="0">
        <thead>
          <tr>
            <th>Store</th>
            <th>Location</th>
          </tr>
        </thead>
        <tbody>
          <!-- Table data will be populated here -->
        </tbody>
      </table>
    </div>
  </div>
</div>
</div>

<!-- Updated modal HTML with two columns per row -->
<div class="modal" id="memberDetailsModal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
  <div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title">Member Details</h5>
      <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <form id="memberDetailsForm">
        <div class="form-row">
          <div class="col-md-6">
            <div class="form-group">
              <label for="FirstName">First Name</label>
              <input type="text" class="form-control" id="FirstName" readonly>
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-group">
              <label for="Lname">Last Name</label>
              <input type="text" class="form-control" id="Lname" readonly>
            </div>
          </div>
        </div>
        <div class="form-row">
          <div class="col-md-6">
            <div class="form-group">
              <label for="Country">Country</label>
              <input type="text" class="form-control" id="Country" readonly>
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-group">
              <label for="CityMunicipality">City/Municipality</label>
              <input type="text" class="form-control" id="CityMunicipality" readonly>
            </div>
          </div>
        </div>
        <div class="form-row">
          <div class="col-md-6">
            <div class="form-group">
              <label for="Region">Region</label>
              <input type="text" class="form-control" id="Region" readonly>
            </div>
          </div>
          <div class="col-md-6">
            <div class="form-group">
              <label for="Club">Club</label>
              <input type="text" class="form-control" id="Club" readonly>
            </div>
          </div>
        </div>
      </form>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
    </div>
  </div>
</div>
</div>

<!-- Bootstrap JS (requires jQuery) -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
  $('#toggleFieldsBtn').click(function() {
    $('.additional-fields').slideToggle();
  });

  // DataTable initialization
  $('#dataTable').DataTable({
    responsive: true // Make the datatable responsive
  });
  
  function concatenateUrlParams() {
      var params = {};
      window.location.search.substr(1).split("&").forEach(function(item) {
          var param = item.split("=");
          params[param[0]] = decodeURIComponent(param[1]);
      });
  
      // Concatenate parameters with a string variable
      var get = "";
      for (var key in params) {
          if (params.hasOwnProperty(key)) {
              get += key + "=" + params[key] + "&";
          }
      }
      // Remove the trailing "&"
      get = get.slice(0, -1);
      
      return get;
  }
  // Handle form submission
  $('#searchForm').submit(function(event) {
    //event.preventDefault(); // Prevent default form submission
    // Here you can write code to handle the form submission and populate the table data
    // Example:
    // $.ajax({
    //   type: 'POST',
    //   url: 'search.php', // Your search endpoint
    //   data: $(this).serialize(),
    //   success: function(response) {
    //     // Assuming response is JSON data containing search results
    //     // You need to parse the response and populate the table with the data
    //     $('#dataTable tbody').html(''); // Clear existing table data
    //     $.each(response, function(index, item) {
    //       $('#dataTable tbody').append('<tr><td>' + item.store + '</td><td>' + item.location + '</td></tr>');
    //     });
    //   }
    // });
  });
  var subdomain = window.location.hostname.split('.')[0]; // Get subdomain
  var realSubdomain = '';
  if (subdomain !== 'www') {
      realSubdomain=subdomain;
  }
  $.ajax({
      url: 'http://' + window.location.hostname + '/eagles/api.php?user=' + realSubdomain,
      type: 'POST',
      dataType: 'json',
      data: { TYPE: 'user' }, // Send TYPE: 'user' as data
      success: function(data) {
          // Print the JSON data to the console
          var member = data[0]; // Assuming you only fetch one member
            $('#FirstName').val(member.FirstName);
            $('#Lname').val(member.Lname);
            $('#Country').val(member.Country);
            $('#CityMunicipality').val(member.CityMunicipality);
            $('#Region').val(member.Region);
            $('#Club').val(member.Club);
      
            // Show the modal
            $('#memberDetailsModal').modal('show');
      },
      error: function(xhr, status, error) {
          // Handle errors if any
          console.error("Failed to fetch data:", error);
      }
  });
  
  $.ajax({
      url: 'http://' + window.location.hostname + '/eagles/api.php?user=' + realSubdomain,
        type: 'POST',
        dataType: 'json',
        data: { TYPE: 'establishments' }, // Send TYPE: 'user' as data
        success: function(data) {
            var select = $('#category');
            select.empty();
            select.append($('<option>').text('Select...').attr('value', ''));
            
            data=JSON.parse(data[0].establishment_json)
            data=data.establishments
            //console.log(data);
            // Iterate over each establishment
            $.each(data, function(index, establishment) {
                var category = establishment.category;
                var establishmentType = establishment.establishment_type.name;
                
                // Check if the optgroup already exists
                var optgroup = select.find('optgroup[label="' + category + '"]');
                if (optgroup.length === 0) {
                    optgroup = $('<optgroup>').attr('label', category);
                    select.append(optgroup);
                }
                
                // Add option under the respective optgroup
                optgroup.append($('<option>').text(establishmentType).attr('value', establishmentType));
            });
        },
        error: function(xhr, status, error) {
            // Handle errors if any
            console.error("Failed to fetch data:", error);
        }
    });
    $.ajax({
        url: 'http://' + window.location.hostname + '/eagles/api.php?user=' + realSubdomain + '&' + concatenateUrlParams(),
        type: 'POST',
        dataType: 'json',
        data: { TYPE: 'discounts' }, // Send TYPE: 'user' as data
        success: function(data) {
            
            if ($.fn.DataTable.isDataTable('#dataTable')) {
                // If DataTable is already initialized, destroy it
                $('#dataTable').DataTable().destroy();
            }
        
            $('#dataTable').DataTable({
                data: data,
                columns: [
                    { data: 'store_name_with_branch' },
                    { data: 'location' },
                    
                ],
                columnDefs: [
                    { responsivePriority: 1, targets: 1 }, // Set priority for responsiveness
                    { width: '75vw', targets: 0 } // Set width of first column to 75%
                    ,{ searchable: true, targets: [0, 1] }
                ]
            });
        },
        error: function(xhr, status, error) {
            // Handle errors if any
            console.error("Failed to fetch data:", error);
        }
    });

    
    
    // Function to check if an image is dark
    var backgroundImages = [
        'https://source.unsplash.com/random/1920x1080',
        'https://source.unsplash.com/random/1920x1081',
        'https://source.unsplash.com/random/1920x1082'
    ];
    var brightnessThreshold = 100; // Adjust as needed

    async function isDark(imageUrl, threshold) {
        return new Promise((resolve, reject) => {
            var img = new Image();
            img.crossOrigin = 'Anonymous'; // Allow cross-origin images
            img.onload = function() {
                var canvas = document.createElement('canvas');
                var ctx = canvas.getContext('2d');
                canvas.width = img.width;
                canvas.height = img.height;
                ctx.drawImage(img, 0, 0);
                var imageData = ctx.getImageData(0, 0, img.width, img.height);
                var brightness = 0;
                for (var i = 0; i < imageData.data.length; i += 4) {
                    brightness += imageData.data[i] * 0.299 + imageData.data[i + 1] * 0.587 + imageData.data[i + 2] * 0.114;
                }
                brightness = brightness / (img.width * img.height);
                resolve(brightness < threshold);
            };
            img.onerror = function() {
                reject(new Error('Failed to load image: ' + imageUrl));
            };
            img.src = imageUrl;
        });
    }
    
    $(document).ready(async function() {
        // Other code remains unchanged
    
        // Filter dark images
        var darkImages = [];
        for (const imageUrl of backgroundImages) {
            try {
                if (await isDark(imageUrl, brightnessThreshold)) {
                    darkImages.push(imageUrl);
                }
            } catch (error) {
                console.error(error);
            }
        }
    
        // Choose a random dark image
        var randomIndex = Math.floor(Math.random() * darkImages.length);
        var randomDarkImage = darkImages[randomIndex];
    
        // Set the background image
        $('body').css('background-image', 'url(' + randomDarkImage + ')');
    });

  });
  
</script>
</body>
</html>


