1737192474a:1:{s:24:"dashboard/allocation.htm";a:10:{s:8:"fileName";s:24:"dashboard/allocation.htm";s:7:"content";s:35867:"title = "Allocation"
url = "/allocation"
layout = "Dashboard"
is_hidden = 0

[session]
security = "user"
allowedUserGroups[] = "admin"
allowedUserGroups[] = "supplier"
redirect = "dashboard/login"
==
<?php
  use Yuren\BaliTiket\Models\Ticket;
  use Yuren\BaliTiket\Models\Allocation;
  use Yuren\BaliTiket\Models\Rateplan;

  use Winter\Storm\Auth\AuthManager;
  use Auth;
  use Carbon\Carbon;

  function onStart()
  {
    $user = Auth::getUser();
    if ($user) {
      $this['vendor'] = $user->vendor;
      $this['tickets'] = Ticket::orderBy('created_at', 'desc')->where('vendor_id', $user->vendor)->get();
      $this['rateplans'] = Rateplan::orderBy('created_at', 'desc')->where('vendor_id', $user->vendor)->get();
      $this['allocations'] = Allocation::orderBy('created_at', 'desc')->where('vendor_id', $user->vendor)->get();
    }

    // Get the selected month from request, default to current month
    $selectedMonth = Input::get('month', Carbon::now()->format('m-Y'));
    $this['selectedMonth'] = Input::get('month', Carbon::now()->format('m-Y'));

    // Get the first and last day of the selected month
    $startDate = Carbon::createFromFormat('m-Y', $selectedMonth)->startOfMonth();
    $endDate = Carbon::createFromFormat('m-Y', $selectedMonth)->endOfMonth();

    // If the selected month is the current month, start from today and add 30 days
    if ($startDate->isCurrentMonth()) {
      $startDate = Carbon::now(); // Start from today
      $endDate = Carbon::now()->addDays(30); // Add 30 days from today
    }

    // Generate the dates for the selected range
    $this['dates'] = collect();
    for ($date = $startDate; $date->lte($endDate); $date->addDay()) {
      $this['dates']->push($date->copy());
    }

    // Generate options for month selection (up to 2 years ahead)
    $currentMonth = Carbon::now();
    $endMonth = Carbon::now()->addYears(2);
    $this['option_dates'] = collect();
    for ($month = $currentMonth; $month->lte($endMonth); $month->addMonth()) {
      $this['option_dates']->push($month->copy());
    }

    $this['ticket'] = Ticket::make();
    $this['allocation'] = Allocation::make();
  }

  function onUpdate()
  {
    date_default_timezone_set('Asia/Singapore');
    $dateNow = date('Y-m-d H:i:s');

    $vendor_id = Input::post('vendor_id');
    $filter_type = Input::post('filter_type');
    $percentage = Input::post('percentage');
    $value = Input::post('value');

    // Ambil bulan dari URL atau default jika tidak ada
    $month = Input::get('month', date('m-Y'));

    // Decode JSON data dari 'data_save'
    $data_save = json_decode(Input::post('data_save'), true);

    // Loop melalui data untuk update alokasi
    foreach ($data_save as $data) {

      $allocation = Allocation::where('vendor_id', $vendor_id)
      ->where('ticket_id', $data['ticket_id'])
      ->where('date', $data['date'])
      ->first();

      if ($allocation) {
        // Update record yang ada
        if ($data['type'] === "availability") {
          $allocation->availability = $value;
        }

        if ($data['type'] === "price") {
          // Decode JSON rateplans
          $rateplans = $allocation->rateplans ?? []; // Pastikan selalu array

          $found = false;
          foreach ($rateplans as &$rateplan) {
            if ($rateplan['rateplan'] == $data['rateplan_id']) {
              $rateplan['fixed_price'] = $value;
              $found = true;
              break;
            }
          }

          // Jika tidak ditemukan, tambahkan rateplan baru
          if (!$found) {
            $rateplans[] = [
            'rateplan' => $data['rateplan_id'],
            'fixed_price' => $value,
            ];
          }

          // Simpan kembali rateplans
          $allocation->rateplans = $rateplans;
        }

        $allocation->updated_at = $dateNow;
        $allocation->save();

      } else {
        // Buat record baru jika tidak ada
        $newAllocation = new Allocation();
        $newAllocation->vendor_id = $vendor_id;
        $newAllocation->ticket_id = $data['ticket_id'];
        $newAllocation->date = $data['date'];

        if ($data['type'] === "availability") {
          $newAllocation->availability = $value;
        }

        if ($data['type'] === "price") {
          $newAllocation->rateplans = [
          [
          'rateplan' => $data['rateplan_id'],
          'fixed_price' => $value,
          ]
          ];
        }

        $newAllocation->created_at = $dateNow;
        $newAllocation->updated_at = $dateNow;
        $newAllocation->save();
      }
    }

    if ($month) {
      // Redirect ke URL yang sama dengan parameter bulan tetap
      return redirect()->to('https://main.tiketxplorer.com/allocation?month=' . $month);
    } else {
      // Refresh page to reflect changes
      return redirect()->refresh();
    }
  }


  function onSave()
  {
    date_default_timezone_set('Asia/Singapore');
    $dateNow = date('Y-m-d H:i:s');

    $vendor_id = Input::post('vendor_id');
    $type2 = Input::post('type2');
    $optionrate1 = Input::post('optionrate1');
    $optionrate2 = Input::post('optionrate2');
    $value2 = Input::post('value2'); 

    // Decode JSON data dari 'data_save'
    $dates2 = json_decode(Input::post('dates2'), true);
    $data_save2 = json_decode(Input::post('data_save2'), true);

    // Loop melalui data untuk update alokasi
    foreach ($data_save2 as $data) {
      foreach ($dates2 as $dateRange) {
        $startDate = new DateTime($dateRange['start_date']);
        $endDate = new DateTime($dateRange['end_date']);
        $endDate->modify('+1 day'); // Tambahkan satu hari agar termasuk tanggal akhir

        // Loop melalui semua tanggal dari start_date sampai end_date
        for ($date = $startDate; $date < $endDate; $date->modify('+1 day')) {
          $currentDate = $date->format('Y-m-d');

          $allocation = Allocation::where('vendor_id', $vendor_id)
          ->where('ticket_id', $data['ticket_id'])
          ->where('date', $currentDate)
          ->first();

          if (!$allocation) {
            // Jika tidak ada, buat alokasi baru
            $allocation = new Allocation();
            $allocation->vendor_id = $vendor_id;
            $allocation->ticket_id = $data['ticket_id'];
            $allocation->date = $currentDate;
          }

          // Update allocation berdasarkan tipe
          if ($data['type'] === "availability") {
            $allocation->availability = $value2;
          } elseif ($data['type'] === "price") {
            $allocation->rateplans = $this->updateRateplans(
            $allocation->rateplans ?? [],
            $data['rateplan_id'],
            $optionrate1,
            $optionrate2,
            $value2,
            $vendor_id,
            $data['ticket_id']
            );
          }

          $allocation->updated_at = $dateNow;
          $allocation->save();
        }
      }
    }

    // Ambil bulan dari URL atau default jika tidak ada
    $month = Input::get('month', date('m-Y'));

    if ($month) {
      // Redirect ke URL yang sama dengan parameter bulan tetap
      return redirect()->to('https://main.tiketxplorer.com/allocation?month=' . $month);
    } else {
      // Refresh page to reflect changes
      return redirect()->refresh();
    }
  }

  /**
  * Update rateplans berdasarkan tipe operasi.
  */
  private function updateRateplans($rateplans, $rateplan_id, $optionrate1, $optionrate2, $value2, $vendor_id, $ticket_id)
  {
    $found = false;
    $datarateplan = Rateplan::where('vendor_id', $vendor_id)
    ->where('ticket_id', $ticket_id)
    ->where('id', $rateplan_id)
    ->first();

    foreach ($rateplans as &$rateplan) {
      if ($rateplan['rateplan'] == $rateplan_id) {
        // Jika ditemukan, update fixed_price
        $found = true;

        if ($optionrate1 === "set") {
          $rateplan['fixed_price'] = $value2;
        } elseif ($optionrate1 === "increase") {
          if ($optionrate2 === "amount") {
            $rateplan['fixed_price'] += $value2;
          } elseif ($optionrate2 === "percentage") {
            $rateplan['fixed_price'] += ($rateplan['fixed_price'] * $value2 / 100);
          }
        } elseif ($optionrate1 === "decrease") {
          if ($optionrate2 === "amount") {
            $rateplan['fixed_price'] -= $value2;
          } elseif ($optionrate2 === "percentage") {
            $rateplan['fixed_price'] -= ($rateplan['fixed_price'] * $value2 / 100);
          }
        }

        // Pastikan fixed_price tidak negatif
        $rateplan['fixed_price'] = max(0, $rateplan['fixed_price']);
        break;
      }
    }

    if (!$found) {
      // Jika rateplan tidak ditemukan, tambahkan baru
      $newPrice = $datarateplan ? $datarateplan['fixed_price'] : 0;

      if ($optionrate1 === "set") {
        $newPrice = $value2;
      } elseif ($optionrate1 === "increase") {
        if ($optionrate2 === "amount") {
          $newPrice += $value2;
        } elseif ($optionrate2 === "percentage") {
          $newPrice += ($newPrice * $value2 / 100);
        }
      } elseif ($optionrate1 === "decrease") {
        if ($optionrate2 === "amount") {
          $newPrice -= $value2;
        } elseif ($optionrate2 === "percentage") {
          $newPrice -= ($newPrice * $value2 / 100);
        }
      }

      $rateplans[] = [
      'rateplan' => $rateplan_id,
      'fixed_price' => max(0, $newPrice),
      ];
    }

    return $rateplans;
  }



?>
==
<!-- Content -->

<div class="container-xxl flex-grow-1 container-p-y">
  <div class="row">


    <div class="col-12 col-xl-6 col-sm-6 mb-4">
      <div class="card">
        <div class="card-header header-elements">
          <h5 class="card-title mb-0"></h5>
        </div>
        <div class="card-body">
          <form id="form-filter" data-request="onUpdate" method="POST" enctype="multipart/form-data" >
            <div class="row g-0">
              <div class="col-md-6 p-2">
                <select class="form-select w-100" name="filter_type" id="filter-type">
                  <option value="Availability">Availability</option>
                  <option value="Price">Price</option>
                </select>
              </div>
              <div class="col-md-6 p-2">
                <input type="text" class="form-control numeral-mask" id="value" name="value" placeholder="Enter value" />
              </div>
              <div class="col-md-12 p-2">

                <input type="hidden" id="vendor_id" name="vendor_id" value="{{user.vendor}}">
                <input type="hidden" id="data_save" name="data_save" value="" required>

                <button type="submit" class="btn btn-primary px-4 py-2">Submit</button>
                <button id="reset-selection" class="btn btn-secondary px-4 py-2 ms-3">Clear Selection</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- recent bookings -->
    <div class="col-12 col-xl-12 col-sm-12 mb-4">
      <div class="card">
        <div class="card-header header-elements">
          <h5 class="card-title mb-0 w-100">
            Allocation 
            <span class="float-end align-middle"><button id="btn-modal-bulkupdate" class="btn btn-success px-4 py-2 ms-3" data-bs-toggle="modal" data-bs-target="#bulkUpdate"><i class="ti ti-edit me-1" style="font-size:17px"></i> Bulk Update</button></span>
          </h5>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-bordered" style="font-size: 11px;">
              <thead>
                <tr>
                  <th class="text-center align-middle" rowspan="2" style="min-width: 150px; position: sticky; left: 0; background-color: #F6F6F6; z-index: 3;">
                    <select class="form-select w-100" id="filter-month">
                      {% for option_date in option_dates %}
                      <option value="{{ option_date|date('m-Y') }}" {{ (option_date|date('m-Y') == selectedMonth) ? 'selected' : '' }}>
                        {{ option_date|date('M Y') }}
                      </option>
                      {% endfor %}
                    </select>
                  </th>

                  {% set currentMonth = null %}
                  {% set daysInMonth = 0 %}
                  {% for date in dates %}
                  {% if date|date('F') != currentMonth %}
                  {% if currentMonth is not null %}
                  <th class="text-center bg-dark text-white fw-bold" colspan="{{ daysInMonth }}" style="width: 80%;">{{ currentMonth }}</th>
                  {% endif %}
                  {% set currentMonth = date|date('F') %}
                  {% set daysInMonth = 1 %}
                  {% else %}
                  {% set daysInMonth = daysInMonth + 1 %}
                  {% endif %}
                  {% endfor %}
                  <th class="text-center bg-dark text-white fw-bold" colspan="{{ daysInMonth }}" style="width: 80%;">{{ currentMonth }}</th>
                </tr>
                <tr class="overflow-auto" style="overflow-x: auto; white-space: nowrap;">
                  {% for date in dates %}
                  <th class="text-center fw-bold" style="min-width: 50px; background-color: #FFFADE">
                    {{ date|date('D') }}<br>
                    {{ date|date('j') }}
                  </th>
                  {% endfor %}
                </tr>
              </thead>


              <tbody>
                {% for ticket in tickets %}
                <tr class="overflow-auto fw-bold" style="overflow-x: auto; white-space: nowrap; background-color: #E2FFDD;">
                  <th class="list-ticket" style="background-color: #E2FFDD;"><p class="mb-0">{{ ticket.name }}</p></th>
                  {% for date in dates %}
                  <td class="text-center" style="min-width: 50px;" data-type="availability" data-ticket="{{ticket.id}}" data-date="{{date|date('Y-m-d')}}">{{ allocation.checkAvailability(user.vendor, ticket.id, date|date('Y-m-d')) }}</td>
                  {% endfor %}
                </tr>
                
                {% set filtered_rateplans = [] %}
                {% for rateplan in rateplans %}
                {% if rateplan.ticket_id == ticket.id %}
                {% set filtered_rateplans = filtered_rateplans | merge([rateplan]) %}
                {% endif %}
                {% endfor %}

                {% for rateplan in filtered_rateplans %}
                <tr class="overflow-auto" style="overflow-x: auto; white-space: nowrap;">
                  <th class="list-price"><p class="mb-0"><i class="ti ti-coin me-1" style="font-size:17px"></i> {{rateplan.name}}</p></th>
                  {% for date in dates %}
                  <td class="text-center" style="min-width: 50px;" data-type="price" data-ticket="{{ticket.id}}" data-rateplan="{{rateplan.id}}" data-date="{{date|date('Y-m-d')}}">{{ allocation.checkPrice(user.vendor, ticket.id, rateplan.id, date|date('Y-m-d')) }}</td>
                  {% endfor %}
                </tr>
                {% endfor %}

                {% endfor %}
              </tbody>
            </table>
          </div>
          <!-- end recent bookings -->

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

    <!-- modal bulk update -->
    <div class="modal fade" id="bulkUpdate" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered modal-xl modal-dialog-scrollable">
        <form class="modal-content" id="form-bulk-update" data-request="onSave" method="POST" enctype="multipart/form-data">
          <div class="modal-header">
            <h1 class="modal-title fs-5" id="exampleModalLabel">Bulk Update</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="row g-0">
              <div class="col-md-12 row g-0">
                <div class="col-1 px-1 my-auto fw-semibold text-center">
                  Set : 
                </div>
                <div class="col-3 px-1">
                  <select class="form-select w-100" name="type2" id="type2">
                    <option value="Availability">Availability</option>
                    <option value="Price">Price</option>
                  </select>
                </div>
                <div class="col-1 px-1 my-auto fw-semibold text-center">
                  To : 
                </div>
                <div class="col-2 px-1 d-none" id="option-rate-1">
                  <select class="form-select w-100" name="optionrate1" id="optionrate1">
                    <option value="set">Set to</option>
                    <option value="increase">Increase by</option>
                    <option value="decrease">Decrease by</option>
                  </select>
                </div>
                <div class="col-3 px-1">
                  <input type="text" class="form-control numeral-mask" id="value2" name="value2" placeholder="Enter value" />
                </div>
                <div class="col-2 px-1 d-none" id="option-rate-2">
                  <select class="form-select w-100" name="optionrate2" id="optionrate2">
                    <option value="amount">Amount</option>
                    <option value="percentage">Percentage</option>
                  </select>
                </div>
              </div>

              <hr class="my-3" />

              <div class="col-md-12">
                <div id="repeater">
                  <div class="row g-0 align-items-center mb-3">
                    <div class="col-4 px-1">
                      <input type="text" class="form-control flatpickr-range flatpickr-range-0" name="dates" placeholder="YYYY-MM-DD to YYYY-MM-DD" />
                    </div>
                    <div class="col-6 px-2 my-auto">
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Sun</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Mon</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Tue</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Wed</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Thu</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Fri</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Sat</label>
                      </div>
                    </div>
                    <div class="col-2 px-1">
                      <button type="button" class="btn btn-danger remove">Remove</button>
                    </div>
                  </div>
                </div>
                <button type="button" class="btn btn-primary" id="add">Add Date Range</button>
              </div>

              <hr class="my-3" />

              <div class="col-md-12">
                {% for ticket in tickets %}
                <div class="row g-0 mb-3 border border-1 border-secondary rounded-2">
                  <div class="col-md-12 p-2 fw-semibold rounded-2" style="background-color: #FFFADE">
                    <span class="me-2 check-availability"><input class="form-check-input checkbox-availability" type="checkbox" data-ticket="{{ticket.id}}" name="availability" value=""/></span>
                    {{ticket.name}}
                  </div>

                  {% set filtered_rateplans = [] %}
                  {% for rateplan in rateplans %}
                  {% if rateplan.ticket_id == ticket.id %}
                  {% set filtered_rateplans = filtered_rateplans | merge([rateplan]) %}
                  {% endif %}
                  {% endfor %}

                  {% for rateplan in filtered_rateplans %}
                  <div class="col-md-12 p-2">
                    <span class="me-2 check-price d-none"><input class="form-check-input checkbox-rateplan" type="checkbox" data-ticket="{{ticket.id}}" data-rateplan="{{rateplan.id}}" name="rateplan" value="" /></span>
                    {{rateplan.name}}
                  </div>
                  {% endfor %}

                </div>
                {% endfor %}
              </div>

            </div>
          </div>
          <div class="modal-footer">
            <input type="hidden" id="vendor_id" name="vendor_id" value="{{user.vendor}}" required>
            <input type="hidden" id="dates2" name="dates2" value="" required>
            <input type="hidden" id="data_save2" name="data_save2" value="" required>
            
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
        </form>
      </div>
    </div>
    <!-- end modal bulk update -->

  </div>
</div>
<!-- / Content -->


<!-- css -->
<style>
  .table-responsive {
    overflow-x: auto; 
  }

  th, td {
    min-width: 30px;
    padding: 8px!important;
  }

  th[scope="row"], th:first-child, td:first-child {
    position: sticky;
    left: 0;
    z-index: 1; 
    background-color: white;
  }
  .list-ticket, .list-price{
    font-size: 11px!important;
    letter-spacing: unset!important;
  }
  .list-ticket p {
    white-space: normal;
    word-wrap: break-word; 
    width: 200px; 
  }
  td {
    cursor: pointer;
  }
  table td {
    user-select: none;
  }
  td.selected {
    background-color: #AFDCFC; 
  }
</style>

<!-- js -->
{% put scripts %}
<script type="text/javascript"> 
  document.addEventListener('DOMContentLoaded', function () {
    var tableCells = document.querySelectorAll('table td');
    var selectedType = null;
    var selectedData = [];
    var draggingData = null;
    var isDragging = false;
    var isSelecting = true;

    // Elemen input yang akan di-update
    var inputDataSave = document.getElementById('data_save');
    var filterType = document.getElementById('filter-type');

    // Fungsi untuk update filter-type
    function updateFilterType(type) {
      if (type === 'availability') {
        filterType.value = 'Availability';
      } else if (type === 'price') {
        filterType.value = 'Price';
      }
    }

    // Event listener pada setiap cell untuk mulai selection
    tableCells.forEach(function (cell) {
      cell.addEventListener('mousedown', function (event) {
        event.preventDefault();

        isDragging = true;
        isSelecting = true;

        var cellType = this.getAttribute('data-type');
        var cellDate = this.getAttribute('data-date');
        var cellRateplan = this.getAttribute('data-rateplan');
        var cellTicket = this.getAttribute('data-ticket');

            // Jika tipe yang berbeda sudah dipilih sebelumnya
        if (selectedType && selectedType !== cellType) {
          alert('You cannot select a different type. Please stick to ' + selectedType + ' cells.');
          isDragging = false;
          return;
        }

            // Set selectedType berdasarkan tipe cell yang dipilih
        if (!selectedType) {
          selectedType = cellType;
          updateFilterType(selectedType);
        }

        draggingData = {
          date: cellDate,
          ticket_id: cellTicket,
          rateplan_id: cellRateplan,
          type: cellType,
        };

        if (!this.classList.contains('selected')) {
          selectedData.push(draggingData);
          this.classList.add('selected');
        } else {
          isSelecting = false;
          selectedData = selectedData.filter(function (data) {
            return data.date !== cellDate || data.ticket_id !== cellTicket || data.rateplan_id !== cellRateplan || data.type !== cellType;
          });
          this.classList.remove('selected');
        }

            // Update input hidden
        inputDataSave.value = JSON.stringify(selectedData);
      });

        // Mousemove event untuk melakukan selection
      cell.addEventListener('mousemove', function (event) {
        if (isDragging && draggingData) {
          var cellDate = this.getAttribute('data-date');
          var cellRateplan = this.getAttribute('data-rateplan');
          var cellType = this.getAttribute('data-type');
          var cellTicket = this.getAttribute('data-ticket');

                // Lakukan aksi hanya jika tipe sel sama dengan yang dipilih
          if (cellType === selectedType) {
            var isCellSelected = this.classList.contains('selected');

            if (isSelecting && !isCellSelected) {
              var newDraggingData = {
                date: cellDate,
                ticket_id: cellTicket,
                rateplan_id: cellRateplan,
                type: cellType,
              };

              selectedData.push(newDraggingData);
              this.classList.add('selected');
            } else if (!isSelecting && isCellSelected) {
              selectedData = selectedData.filter(function (data) {
                return data.date !== cellDate || data.ticket_id !== cellTicket || data.rateplan_id !== cellRateplan || data.type !== cellType;
              });
              this.classList.remove('selected');
            }

                    // Update hidden input
            inputDataSave.value = JSON.stringify(selectedData);
          }
        }
      });

        // Mouseup event untuk mengakhiri drag
      cell.addEventListener('mouseup', function () {
        isDragging = false;
        draggingData = null;

        if (selectedData.length === 0) {
          selectedType = null;
          filterType.value = '';
        }
      });
    });

    // Hentikan drag jika mouse dilepas di luar table
    document.addEventListener('mouseup', function () {
      isDragging = false;
      draggingData = null;
    });

    // Tombol reset untuk menghapus semua pilihan
    document.getElementById('reset-selection').addEventListener('click', function (event) {
      event.preventDefault();
      tableCells.forEach(function (cell) {
        cell.classList.remove('selected');
      });
      selectedType = null;
      selectedData = [];

      inputDataSave.value = '';
      filterType.value = '';
    });
  });




// Perubahan bulan yang dipilih
document.addEventListener('DOMContentLoaded', function () {
  var filterMonth = document.getElementById('filter-month');

  filterMonth.addEventListener('change', function () {
    // Ambil nilai bulan yang dipilih
    var selectedMonth = filterMonth.value;

    // Kirim form untuk memfilter tanggal berdasarkan bulan
    var form = document.createElement('form');
    form.method = 'GET';
    form.action = '';  
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'month';
    input.value = selectedMonth;
    form.appendChild(input);
    document.body.appendChild(form);
    form.submit();
  });
});

// Price input formatting (Cleave.js integration)
document.addEventListener('DOMContentLoaded', function () {
  var numeralMask = document.getElementById('value');
  var numeralMask2 = document.getElementById('value2');

  if (numeralMask) {
    new Cleave(numeralMask, {
      numeral: true,
      numeralThousandsGroupStyle: 'thousand'
    });
  }

  if (numeralMask2) {
    new Cleave(numeralMask2, {
      numeral: true,
      numeralThousandsGroupStyle: 'thousand'
    });
  }

  // Hapus koma sebelum form disubmit
  document.querySelector('form').addEventListener('submit', function (event) {
    numeralMask.value = numeralMask.value.replace(/,/g, '');
  });

  document.querySelector('#form-bulk-update').addEventListener('submit', function (event) {
    numeralMask2.value = numeralMask2.value.replace(/,/g, '');
  });
});


document.addEventListener('DOMContentLoaded', function () {
  var type2 = document.getElementById('type2');
  var optionRate1 = document.getElementById('option-rate-1');
  var optionRate2 = document.getElementById('option-rate-2');
  var checkAvailability = $('.check-availability');
  var checkPrice = $('.check-price');

  // Function to toggle discount container based on filter type
  function toggleOptionRate() {
    if (type2.value === 'Price') {
      optionRate1.classList.remove('d-none');
      optionRate2.classList.remove('d-none');
      checkAvailability.addClass('d-none');
      checkPrice.removeClass('d-none');
    } else {
      optionRate1.classList.add('d-none');
      optionRate2.classList.add('d-none');
      checkAvailability.removeClass('d-none');
      checkPrice.addClass('d-none');
    }
  }

  // Initial check in case the page loads with "Discount" pre-selected
  toggleOptionRate();

  // Add event listener for changes in the filter type
  type2.addEventListener('change', toggleOptionRate);
});


// repeater date
$(document).ready(function(){
  let itemIndex = 1;

  // Fungsi untuk menginisialisasi flatpickr pada elemen dengan class "flatpickr-range"
  function initializeFlatpickr() {
    $('.flatpickr-range').each(function() {
      if (!$(this).hasClass('flatpickr-initialized')) {
        $(this).flatpickr({
          mode: 'range'
        });
        $(this).addClass('flatpickr-initialized');
      }
    });
  }

  // Saat tombol "Add Item" diklik
  $("#add").click(function(){
    $("#repeater").append(
      `<div class="row g-0 align-items-center mb-3">
      <div class="col-4 px-1">
      <input type="text" class="form-control flatpickr-range flatpickr-range-${itemIndex}" placeholder="YYYY-MM-DD to YYYY-MM-DD" />
      </div>
      <div class="col-6 px-2 my-auto">
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Sun</label>
      </div>
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Mon</label>
      </div>
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Tue</label>
      </div>
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Wed</label>
      </div>
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Thu</label>
      </div>
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Fri</label>
      </div>
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Sat</label>
      </div>
      </div>
      <div class="col-2 px-1">
      <button type="button" class="btn btn-danger remove">Remove</button>
      </div>
      </div>`
      );
    itemIndex++;
    // Panggil kembali fungsi flatpickr setelah item ditambahkan
    initializeFlatpickr();
  });

  // Hapus elemen saat tombol remove diklik
  $(document).on('click', '.remove', function(){
    $(this).closest('.row').remove();
  });

  // Inisialisasi flatpickr pada halaman load pertama
  initializeFlatpickr();
});


$(document).ready(function() {
  // Function to update the hidden input with selected date ranges
  function updateDateRanges() {
    var dateRanges = [];

    // Loop through all flatpickr instances to get the selected date ranges
    $('#repeater .flatpickr-range').each(function() {
      var selectedDates = $(this).val().split(" to "); // Split the value by " to "
      if (selectedDates.length === 2) {
        dateRanges.push({
          "start_date": selectedDates[0], // First date
          "end_date": selectedDates[1] // Second date
        });
      }
    });

    // Store the dateRanges array as a JSON string in the hidden input field
    $('#dates2').val(JSON.stringify(dateRanges));
  }

  // Function to update the hidden input with checked ticket info
  function updateCheckedTickets() {
    var checkedTickets = [];

    // Collect checked availability, adult, and children checkboxes
    $('.checkbox-availability:checked').each(function() {
      checkedTickets.push({
        "ticket_id": $(this).data('ticket'), // Get the data-ticket attribute value
        "type": "availability" // Type for availability checkbox
      });
    });

    $('.checkbox-rateplan:checked').each(function() {
      checkedTickets.push({
        "ticket_id": $(this).data('ticket'), // Get the data-ticket attribute value
        "rateplan_id": $(this).data('rateplan'),
        "type": "price" // Type for adult checkbox
      });
    });

    // Store the checkedTickets array as a JSON string in the hidden input field
    $('#data_save2').val(JSON.stringify(checkedTickets));
  }

  // Listen for changes on flatpickr-range inputs
  $('#repeater').on('change', '.flatpickr-range', function() {
    updateDateRanges(); // Update date ranges whenever the input value changes
  });

  // Initialize Flatpickr
  $('.flatpickr-range').flatpickr({
    mode: "range",
    onClose: updateDateRanges // Call the function when the date picker closes
  });

  // Directly listen for changes on the specific checkboxes
  $('.checkbox-availability, .checkbox-rateplan').change(function() {
    updateCheckedTickets(); // Update the checked ticket info whenever any checkbox changes
  });
});



</script>
{% endput %}
<!-- end js -->";s:5:"mtime";i:1731903377;s:6:"markup";s:26107:"<!-- Content -->

<div class="container-xxl flex-grow-1 container-p-y">
  <div class="row">


    <div class="col-12 col-xl-6 col-sm-6 mb-4">
      <div class="card">
        <div class="card-header header-elements">
          <h5 class="card-title mb-0"></h5>
        </div>
        <div class="card-body">
          <form id="form-filter" data-request="onUpdate" method="POST" enctype="multipart/form-data" >
            <div class="row g-0">
              <div class="col-md-6 p-2">
                <select class="form-select w-100" name="filter_type" id="filter-type">
                  <option value="Availability">Availability</option>
                  <option value="Price">Price</option>
                </select>
              </div>
              <div class="col-md-6 p-2">
                <input type="text" class="form-control numeral-mask" id="value" name="value" placeholder="Enter value" />
              </div>
              <div class="col-md-12 p-2">

                <input type="hidden" id="vendor_id" name="vendor_id" value="{{user.vendor}}">
                <input type="hidden" id="data_save" name="data_save" value="" required>

                <button type="submit" class="btn btn-primary px-4 py-2">Submit</button>
                <button id="reset-selection" class="btn btn-secondary px-4 py-2 ms-3">Clear Selection</button>
              </div>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- recent bookings -->
    <div class="col-12 col-xl-12 col-sm-12 mb-4">
      <div class="card">
        <div class="card-header header-elements">
          <h5 class="card-title mb-0 w-100">
            Allocation 
            <span class="float-end align-middle"><button id="btn-modal-bulkupdate" class="btn btn-success px-4 py-2 ms-3" data-bs-toggle="modal" data-bs-target="#bulkUpdate"><i class="ti ti-edit me-1" style="font-size:17px"></i> Bulk Update</button></span>
          </h5>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-bordered" style="font-size: 11px;">
              <thead>
                <tr>
                  <th class="text-center align-middle" rowspan="2" style="min-width: 150px; position: sticky; left: 0; background-color: #F6F6F6; z-index: 3;">
                    <select class="form-select w-100" id="filter-month">
                      {% for option_date in option_dates %}
                      <option value="{{ option_date|date('m-Y') }}" {{ (option_date|date('m-Y') == selectedMonth) ? 'selected' : '' }}>
                        {{ option_date|date('M Y') }}
                      </option>
                      {% endfor %}
                    </select>
                  </th>

                  {% set currentMonth = null %}
                  {% set daysInMonth = 0 %}
                  {% for date in dates %}
                  {% if date|date('F') != currentMonth %}
                  {% if currentMonth is not null %}
                  <th class="text-center bg-dark text-white fw-bold" colspan="{{ daysInMonth }}" style="width: 80%;">{{ currentMonth }}</th>
                  {% endif %}
                  {% set currentMonth = date|date('F') %}
                  {% set daysInMonth = 1 %}
                  {% else %}
                  {% set daysInMonth = daysInMonth + 1 %}
                  {% endif %}
                  {% endfor %}
                  <th class="text-center bg-dark text-white fw-bold" colspan="{{ daysInMonth }}" style="width: 80%;">{{ currentMonth }}</th>
                </tr>
                <tr class="overflow-auto" style="overflow-x: auto; white-space: nowrap;">
                  {% for date in dates %}
                  <th class="text-center fw-bold" style="min-width: 50px; background-color: #FFFADE">
                    {{ date|date('D') }}<br>
                    {{ date|date('j') }}
                  </th>
                  {% endfor %}
                </tr>
              </thead>


              <tbody>
                {% for ticket in tickets %}
                <tr class="overflow-auto fw-bold" style="overflow-x: auto; white-space: nowrap; background-color: #E2FFDD;">
                  <th class="list-ticket" style="background-color: #E2FFDD;"><p class="mb-0">{{ ticket.name }}</p></th>
                  {% for date in dates %}
                  <td class="text-center" style="min-width: 50px;" data-type="availability" data-ticket="{{ticket.id}}" data-date="{{date|date('Y-m-d')}}">{{ allocation.checkAvailability(user.vendor, ticket.id, date|date('Y-m-d')) }}</td>
                  {% endfor %}
                </tr>
                
                {% set filtered_rateplans = [] %}
                {% for rateplan in rateplans %}
                {% if rateplan.ticket_id == ticket.id %}
                {% set filtered_rateplans = filtered_rateplans | merge([rateplan]) %}
                {% endif %}
                {% endfor %}

                {% for rateplan in filtered_rateplans %}
                <tr class="overflow-auto" style="overflow-x: auto; white-space: nowrap;">
                  <th class="list-price"><p class="mb-0"><i class="ti ti-coin me-1" style="font-size:17px"></i> {{rateplan.name}}</p></th>
                  {% for date in dates %}
                  <td class="text-center" style="min-width: 50px;" data-type="price" data-ticket="{{ticket.id}}" data-rateplan="{{rateplan.id}}" data-date="{{date|date('Y-m-d')}}">{{ allocation.checkPrice(user.vendor, ticket.id, rateplan.id, date|date('Y-m-d')) }}</td>
                  {% endfor %}
                </tr>
                {% endfor %}

                {% endfor %}
              </tbody>
            </table>
          </div>
          <!-- end recent bookings -->

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

    <!-- modal bulk update -->
    <div class="modal fade" id="bulkUpdate" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-dialog-centered modal-xl modal-dialog-scrollable">
        <form class="modal-content" id="form-bulk-update" data-request="onSave" method="POST" enctype="multipart/form-data">
          <div class="modal-header">
            <h1 class="modal-title fs-5" id="exampleModalLabel">Bulk Update</h1>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="row g-0">
              <div class="col-md-12 row g-0">
                <div class="col-1 px-1 my-auto fw-semibold text-center">
                  Set : 
                </div>
                <div class="col-3 px-1">
                  <select class="form-select w-100" name="type2" id="type2">
                    <option value="Availability">Availability</option>
                    <option value="Price">Price</option>
                  </select>
                </div>
                <div class="col-1 px-1 my-auto fw-semibold text-center">
                  To : 
                </div>
                <div class="col-2 px-1 d-none" id="option-rate-1">
                  <select class="form-select w-100" name="optionrate1" id="optionrate1">
                    <option value="set">Set to</option>
                    <option value="increase">Increase by</option>
                    <option value="decrease">Decrease by</option>
                  </select>
                </div>
                <div class="col-3 px-1">
                  <input type="text" class="form-control numeral-mask" id="value2" name="value2" placeholder="Enter value" />
                </div>
                <div class="col-2 px-1 d-none" id="option-rate-2">
                  <select class="form-select w-100" name="optionrate2" id="optionrate2">
                    <option value="amount">Amount</option>
                    <option value="percentage">Percentage</option>
                  </select>
                </div>
              </div>

              <hr class="my-3" />

              <div class="col-md-12">
                <div id="repeater">
                  <div class="row g-0 align-items-center mb-3">
                    <div class="col-4 px-1">
                      <input type="text" class="form-control flatpickr-range flatpickr-range-0" name="dates" placeholder="YYYY-MM-DD to YYYY-MM-DD" />
                    </div>
                    <div class="col-6 px-2 my-auto">
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Sun</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Mon</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Tue</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Wed</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Thu</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Fri</label>
                      </div>
                      <div class="form-check form-check-inline">
                        <input class="form-check-input" type="checkbox" name="days[0][]" checked />
                        <label class="form-check-label">Sat</label>
                      </div>
                    </div>
                    <div class="col-2 px-1">
                      <button type="button" class="btn btn-danger remove">Remove</button>
                    </div>
                  </div>
                </div>
                <button type="button" class="btn btn-primary" id="add">Add Date Range</button>
              </div>

              <hr class="my-3" />

              <div class="col-md-12">
                {% for ticket in tickets %}
                <div class="row g-0 mb-3 border border-1 border-secondary rounded-2">
                  <div class="col-md-12 p-2 fw-semibold rounded-2" style="background-color: #FFFADE">
                    <span class="me-2 check-availability"><input class="form-check-input checkbox-availability" type="checkbox" data-ticket="{{ticket.id}}" name="availability" value=""/></span>
                    {{ticket.name}}
                  </div>

                  {% set filtered_rateplans = [] %}
                  {% for rateplan in rateplans %}
                  {% if rateplan.ticket_id == ticket.id %}
                  {% set filtered_rateplans = filtered_rateplans | merge([rateplan]) %}
                  {% endif %}
                  {% endfor %}

                  {% for rateplan in filtered_rateplans %}
                  <div class="col-md-12 p-2">
                    <span class="me-2 check-price d-none"><input class="form-check-input checkbox-rateplan" type="checkbox" data-ticket="{{ticket.id}}" data-rateplan="{{rateplan.id}}" name="rateplan" value="" /></span>
                    {{rateplan.name}}
                  </div>
                  {% endfor %}

                </div>
                {% endfor %}
              </div>

            </div>
          </div>
          <div class="modal-footer">
            <input type="hidden" id="vendor_id" name="vendor_id" value="{{user.vendor}}" required>
            <input type="hidden" id="dates2" name="dates2" value="" required>
            <input type="hidden" id="data_save2" name="data_save2" value="" required>
            
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            <button type="submit" class="btn btn-success">Submit</button>
          </div>
        </form>
      </div>
    </div>
    <!-- end modal bulk update -->

  </div>
</div>
<!-- / Content -->


<!-- css -->
<style>
  .table-responsive {
    overflow-x: auto; 
  }

  th, td {
    min-width: 30px;
    padding: 8px!important;
  }

  th[scope="row"], th:first-child, td:first-child {
    position: sticky;
    left: 0;
    z-index: 1; 
    background-color: white;
  }
  .list-ticket, .list-price{
    font-size: 11px!important;
    letter-spacing: unset!important;
  }
  .list-ticket p {
    white-space: normal;
    word-wrap: break-word; 
    width: 200px; 
  }
  td {
    cursor: pointer;
  }
  table td {
    user-select: none;
  }
  td.selected {
    background-color: #AFDCFC; 
  }
</style>

<!-- js -->
{% put scripts %}
<script type="text/javascript"> 
  document.addEventListener('DOMContentLoaded', function () {
    var tableCells = document.querySelectorAll('table td');
    var selectedType = null;
    var selectedData = [];
    var draggingData = null;
    var isDragging = false;
    var isSelecting = true;

    // Elemen input yang akan di-update
    var inputDataSave = document.getElementById('data_save');
    var filterType = document.getElementById('filter-type');

    // Fungsi untuk update filter-type
    function updateFilterType(type) {
      if (type === 'availability') {
        filterType.value = 'Availability';
      } else if (type === 'price') {
        filterType.value = 'Price';
      }
    }

    // Event listener pada setiap cell untuk mulai selection
    tableCells.forEach(function (cell) {
      cell.addEventListener('mousedown', function (event) {
        event.preventDefault();

        isDragging = true;
        isSelecting = true;

        var cellType = this.getAttribute('data-type');
        var cellDate = this.getAttribute('data-date');
        var cellRateplan = this.getAttribute('data-rateplan');
        var cellTicket = this.getAttribute('data-ticket');

            // Jika tipe yang berbeda sudah dipilih sebelumnya
        if (selectedType && selectedType !== cellType) {
          alert('You cannot select a different type. Please stick to ' + selectedType + ' cells.');
          isDragging = false;
          return;
        }

            // Set selectedType berdasarkan tipe cell yang dipilih
        if (!selectedType) {
          selectedType = cellType;
          updateFilterType(selectedType);
        }

        draggingData = {
          date: cellDate,
          ticket_id: cellTicket,
          rateplan_id: cellRateplan,
          type: cellType,
        };

        if (!this.classList.contains('selected')) {
          selectedData.push(draggingData);
          this.classList.add('selected');
        } else {
          isSelecting = false;
          selectedData = selectedData.filter(function (data) {
            return data.date !== cellDate || data.ticket_id !== cellTicket || data.rateplan_id !== cellRateplan || data.type !== cellType;
          });
          this.classList.remove('selected');
        }

            // Update input hidden
        inputDataSave.value = JSON.stringify(selectedData);
      });

        // Mousemove event untuk melakukan selection
      cell.addEventListener('mousemove', function (event) {
        if (isDragging && draggingData) {
          var cellDate = this.getAttribute('data-date');
          var cellRateplan = this.getAttribute('data-rateplan');
          var cellType = this.getAttribute('data-type');
          var cellTicket = this.getAttribute('data-ticket');

                // Lakukan aksi hanya jika tipe sel sama dengan yang dipilih
          if (cellType === selectedType) {
            var isCellSelected = this.classList.contains('selected');

            if (isSelecting && !isCellSelected) {
              var newDraggingData = {
                date: cellDate,
                ticket_id: cellTicket,
                rateplan_id: cellRateplan,
                type: cellType,
              };

              selectedData.push(newDraggingData);
              this.classList.add('selected');
            } else if (!isSelecting && isCellSelected) {
              selectedData = selectedData.filter(function (data) {
                return data.date !== cellDate || data.ticket_id !== cellTicket || data.rateplan_id !== cellRateplan || data.type !== cellType;
              });
              this.classList.remove('selected');
            }

                    // Update hidden input
            inputDataSave.value = JSON.stringify(selectedData);
          }
        }
      });

        // Mouseup event untuk mengakhiri drag
      cell.addEventListener('mouseup', function () {
        isDragging = false;
        draggingData = null;

        if (selectedData.length === 0) {
          selectedType = null;
          filterType.value = '';
        }
      });
    });

    // Hentikan drag jika mouse dilepas di luar table
    document.addEventListener('mouseup', function () {
      isDragging = false;
      draggingData = null;
    });

    // Tombol reset untuk menghapus semua pilihan
    document.getElementById('reset-selection').addEventListener('click', function (event) {
      event.preventDefault();
      tableCells.forEach(function (cell) {
        cell.classList.remove('selected');
      });
      selectedType = null;
      selectedData = [];

      inputDataSave.value = '';
      filterType.value = '';
    });
  });




// Perubahan bulan yang dipilih
document.addEventListener('DOMContentLoaded', function () {
  var filterMonth = document.getElementById('filter-month');

  filterMonth.addEventListener('change', function () {
    // Ambil nilai bulan yang dipilih
    var selectedMonth = filterMonth.value;

    // Kirim form untuk memfilter tanggal berdasarkan bulan
    var form = document.createElement('form');
    form.method = 'GET';
    form.action = '';  
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'month';
    input.value = selectedMonth;
    form.appendChild(input);
    document.body.appendChild(form);
    form.submit();
  });
});

// Price input formatting (Cleave.js integration)
document.addEventListener('DOMContentLoaded', function () {
  var numeralMask = document.getElementById('value');
  var numeralMask2 = document.getElementById('value2');

  if (numeralMask) {
    new Cleave(numeralMask, {
      numeral: true,
      numeralThousandsGroupStyle: 'thousand'
    });
  }

  if (numeralMask2) {
    new Cleave(numeralMask2, {
      numeral: true,
      numeralThousandsGroupStyle: 'thousand'
    });
  }

  // Hapus koma sebelum form disubmit
  document.querySelector('form').addEventListener('submit', function (event) {
    numeralMask.value = numeralMask.value.replace(/,/g, '');
  });

  document.querySelector('#form-bulk-update').addEventListener('submit', function (event) {
    numeralMask2.value = numeralMask2.value.replace(/,/g, '');
  });
});


document.addEventListener('DOMContentLoaded', function () {
  var type2 = document.getElementById('type2');
  var optionRate1 = document.getElementById('option-rate-1');
  var optionRate2 = document.getElementById('option-rate-2');
  var checkAvailability = $('.check-availability');
  var checkPrice = $('.check-price');

  // Function to toggle discount container based on filter type
  function toggleOptionRate() {
    if (type2.value === 'Price') {
      optionRate1.classList.remove('d-none');
      optionRate2.classList.remove('d-none');
      checkAvailability.addClass('d-none');
      checkPrice.removeClass('d-none');
    } else {
      optionRate1.classList.add('d-none');
      optionRate2.classList.add('d-none');
      checkAvailability.removeClass('d-none');
      checkPrice.addClass('d-none');
    }
  }

  // Initial check in case the page loads with "Discount" pre-selected
  toggleOptionRate();

  // Add event listener for changes in the filter type
  type2.addEventListener('change', toggleOptionRate);
});


// repeater date
$(document).ready(function(){
  let itemIndex = 1;

  // Fungsi untuk menginisialisasi flatpickr pada elemen dengan class "flatpickr-range"
  function initializeFlatpickr() {
    $('.flatpickr-range').each(function() {
      if (!$(this).hasClass('flatpickr-initialized')) {
        $(this).flatpickr({
          mode: 'range'
        });
        $(this).addClass('flatpickr-initialized');
      }
    });
  }

  // Saat tombol "Add Item" diklik
  $("#add").click(function(){
    $("#repeater").append(
      `<div class="row g-0 align-items-center mb-3">
      <div class="col-4 px-1">
      <input type="text" class="form-control flatpickr-range flatpickr-range-${itemIndex}" placeholder="YYYY-MM-DD to YYYY-MM-DD" />
      </div>
      <div class="col-6 px-2 my-auto">
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Sun</label>
      </div>
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Mon</label>
      </div>
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Tue</label>
      </div>
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Wed</label>
      </div>
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Thu</label>
      </div>
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Fri</label>
      </div>
      <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" name="days[${itemIndex}][]" checked />
      <label class="form-check-label">Sat</label>
      </div>
      </div>
      <div class="col-2 px-1">
      <button type="button" class="btn btn-danger remove">Remove</button>
      </div>
      </div>`
      );
    itemIndex++;
    // Panggil kembali fungsi flatpickr setelah item ditambahkan
    initializeFlatpickr();
  });

  // Hapus elemen saat tombol remove diklik
  $(document).on('click', '.remove', function(){
    $(this).closest('.row').remove();
  });

  // Inisialisasi flatpickr pada halaman load pertama
  initializeFlatpickr();
});


$(document).ready(function() {
  // Function to update the hidden input with selected date ranges
  function updateDateRanges() {
    var dateRanges = [];

    // Loop through all flatpickr instances to get the selected date ranges
    $('#repeater .flatpickr-range').each(function() {
      var selectedDates = $(this).val().split(" to "); // Split the value by " to "
      if (selectedDates.length === 2) {
        dateRanges.push({
          "start_date": selectedDates[0], // First date
          "end_date": selectedDates[1] // Second date
        });
      }
    });

    // Store the dateRanges array as a JSON string in the hidden input field
    $('#dates2').val(JSON.stringify(dateRanges));
  }

  // Function to update the hidden input with checked ticket info
  function updateCheckedTickets() {
    var checkedTickets = [];

    // Collect checked availability, adult, and children checkboxes
    $('.checkbox-availability:checked').each(function() {
      checkedTickets.push({
        "ticket_id": $(this).data('ticket'), // Get the data-ticket attribute value
        "type": "availability" // Type for availability checkbox
      });
    });

    $('.checkbox-rateplan:checked').each(function() {
      checkedTickets.push({
        "ticket_id": $(this).data('ticket'), // Get the data-ticket attribute value
        "rateplan_id": $(this).data('rateplan'),
        "type": "price" // Type for adult checkbox
      });
    });

    // Store the checkedTickets array as a JSON string in the hidden input field
    $('#data_save2').val(JSON.stringify(checkedTickets));
  }

  // Listen for changes on flatpickr-range inputs
  $('#repeater').on('change', '.flatpickr-range', function() {
    updateDateRanges(); // Update date ranges whenever the input value changes
  });

  // Initialize Flatpickr
  $('.flatpickr-range').flatpickr({
    mode: "range",
    onClose: updateDateRanges // Call the function when the date picker closes
  });

  // Directly listen for changes on the specific checkboxes
  $('.checkbox-availability, .checkbox-rateplan').change(function() {
    updateCheckedTickets(); // Update the checked ticket info whenever any checkbox changes
  });
});



</script>
{% endput %}
<!-- end js -->";s:4:"code";s:9535:"
  use Yuren\BaliTiket\Models\Ticket;
  use Yuren\BaliTiket\Models\Allocation;
  use Yuren\BaliTiket\Models\Rateplan;

  use Winter\Storm\Auth\AuthManager;
  use Auth;
  use Carbon\Carbon;

  function onStart()
  {
    $user = Auth::getUser();
    if ($user) {
      $this['vendor'] = $user->vendor;
      $this['tickets'] = Ticket::orderBy('created_at', 'desc')->where('vendor_id', $user->vendor)->get();
      $this['rateplans'] = Rateplan::orderBy('created_at', 'desc')->where('vendor_id', $user->vendor)->get();
      $this['allocations'] = Allocation::orderBy('created_at', 'desc')->where('vendor_id', $user->vendor)->get();
    }

    // Get the selected month from request, default to current month
    $selectedMonth = Input::get('month', Carbon::now()->format('m-Y'));
    $this['selectedMonth'] = Input::get('month', Carbon::now()->format('m-Y'));

    // Get the first and last day of the selected month
    $startDate = Carbon::createFromFormat('m-Y', $selectedMonth)->startOfMonth();
    $endDate = Carbon::createFromFormat('m-Y', $selectedMonth)->endOfMonth();

    // If the selected month is the current month, start from today and add 30 days
    if ($startDate->isCurrentMonth()) {
      $startDate = Carbon::now(); // Start from today
      $endDate = Carbon::now()->addDays(30); // Add 30 days from today
    }

    // Generate the dates for the selected range
    $this['dates'] = collect();
    for ($date = $startDate; $date->lte($endDate); $date->addDay()) {
      $this['dates']->push($date->copy());
    }

    // Generate options for month selection (up to 2 years ahead)
    $currentMonth = Carbon::now();
    $endMonth = Carbon::now()->addYears(2);
    $this['option_dates'] = collect();
    for ($month = $currentMonth; $month->lte($endMonth); $month->addMonth()) {
      $this['option_dates']->push($month->copy());
    }

    $this['ticket'] = Ticket::make();
    $this['allocation'] = Allocation::make();
  }

  function onUpdate()
  {
    date_default_timezone_set('Asia/Singapore');
    $dateNow = date('Y-m-d H:i:s');

    $vendor_id = Input::post('vendor_id');
    $filter_type = Input::post('filter_type');
    $percentage = Input::post('percentage');
    $value = Input::post('value');

    // Ambil bulan dari URL atau default jika tidak ada
    $month = Input::get('month', date('m-Y'));

    // Decode JSON data dari 'data_save'
    $data_save = json_decode(Input::post('data_save'), true);

    // Loop melalui data untuk update alokasi
    foreach ($data_save as $data) {

      $allocation = Allocation::where('vendor_id', $vendor_id)
      ->where('ticket_id', $data['ticket_id'])
      ->where('date', $data['date'])
      ->first();

      if ($allocation) {
        // Update record yang ada
        if ($data['type'] === "availability") {
          $allocation->availability = $value;
        }

        if ($data['type'] === "price") {
          // Decode JSON rateplans
          $rateplans = $allocation->rateplans ?? []; // Pastikan selalu array

          $found = false;
          foreach ($rateplans as &$rateplan) {
            if ($rateplan['rateplan'] == $data['rateplan_id']) {
              $rateplan['fixed_price'] = $value;
              $found = true;
              break;
            }
          }

          // Jika tidak ditemukan, tambahkan rateplan baru
          if (!$found) {
            $rateplans[] = [
            'rateplan' => $data['rateplan_id'],
            'fixed_price' => $value,
            ];
          }

          // Simpan kembali rateplans
          $allocation->rateplans = $rateplans;
        }

        $allocation->updated_at = $dateNow;
        $allocation->save();

      } else {
        // Buat record baru jika tidak ada
        $newAllocation = new Allocation();
        $newAllocation->vendor_id = $vendor_id;
        $newAllocation->ticket_id = $data['ticket_id'];
        $newAllocation->date = $data['date'];

        if ($data['type'] === "availability") {
          $newAllocation->availability = $value;
        }

        if ($data['type'] === "price") {
          $newAllocation->rateplans = [
          [
          'rateplan' => $data['rateplan_id'],
          'fixed_price' => $value,
          ]
          ];
        }

        $newAllocation->created_at = $dateNow;
        $newAllocation->updated_at = $dateNow;
        $newAllocation->save();
      }
    }

    if ($month) {
      // Redirect ke URL yang sama dengan parameter bulan tetap
      return redirect()->to('https://main.tiketxplorer.com/allocation?month=' . $month);
    } else {
      // Refresh page to reflect changes
      return redirect()->refresh();
    }
  }


  function onSave()
  {
    date_default_timezone_set('Asia/Singapore');
    $dateNow = date('Y-m-d H:i:s');

    $vendor_id = Input::post('vendor_id');
    $type2 = Input::post('type2');
    $optionrate1 = Input::post('optionrate1');
    $optionrate2 = Input::post('optionrate2');
    $value2 = Input::post('value2'); 

    // Decode JSON data dari 'data_save'
    $dates2 = json_decode(Input::post('dates2'), true);
    $data_save2 = json_decode(Input::post('data_save2'), true);

    // Loop melalui data untuk update alokasi
    foreach ($data_save2 as $data) {
      foreach ($dates2 as $dateRange) {
        $startDate = new DateTime($dateRange['start_date']);
        $endDate = new DateTime($dateRange['end_date']);
        $endDate->modify('+1 day'); // Tambahkan satu hari agar termasuk tanggal akhir

        // Loop melalui semua tanggal dari start_date sampai end_date
        for ($date = $startDate; $date < $endDate; $date->modify('+1 day')) {
          $currentDate = $date->format('Y-m-d');

          $allocation = Allocation::where('vendor_id', $vendor_id)
          ->where('ticket_id', $data['ticket_id'])
          ->where('date', $currentDate)
          ->first();

          if (!$allocation) {
            // Jika tidak ada, buat alokasi baru
            $allocation = new Allocation();
            $allocation->vendor_id = $vendor_id;
            $allocation->ticket_id = $data['ticket_id'];
            $allocation->date = $currentDate;
          }

          // Update allocation berdasarkan tipe
          if ($data['type'] === "availability") {
            $allocation->availability = $value2;
          } elseif ($data['type'] === "price") {
            $allocation->rateplans = $this->updateRateplans(
            $allocation->rateplans ?? [],
            $data['rateplan_id'],
            $optionrate1,
            $optionrate2,
            $value2,
            $vendor_id,
            $data['ticket_id']
            );
          }

          $allocation->updated_at = $dateNow;
          $allocation->save();
        }
      }
    }

    // Ambil bulan dari URL atau default jika tidak ada
    $month = Input::get('month', date('m-Y'));

    if ($month) {
      // Redirect ke URL yang sama dengan parameter bulan tetap
      return redirect()->to('https://main.tiketxplorer.com/allocation?month=' . $month);
    } else {
      // Refresh page to reflect changes
      return redirect()->refresh();
    }
  }

  /**
  * Update rateplans berdasarkan tipe operasi.
  */
  private function updateRateplans($rateplans, $rateplan_id, $optionrate1, $optionrate2, $value2, $vendor_id, $ticket_id)
  {
    $found = false;
    $datarateplan = Rateplan::where('vendor_id', $vendor_id)
    ->where('ticket_id', $ticket_id)
    ->where('id', $rateplan_id)
    ->first();

    foreach ($rateplans as &$rateplan) {
      if ($rateplan['rateplan'] == $rateplan_id) {
        // Jika ditemukan, update fixed_price
        $found = true;

        if ($optionrate1 === "set") {
          $rateplan['fixed_price'] = $value2;
        } elseif ($optionrate1 === "increase") {
          if ($optionrate2 === "amount") {
            $rateplan['fixed_price'] += $value2;
          } elseif ($optionrate2 === "percentage") {
            $rateplan['fixed_price'] += ($rateplan['fixed_price'] * $value2 / 100);
          }
        } elseif ($optionrate1 === "decrease") {
          if ($optionrate2 === "amount") {
            $rateplan['fixed_price'] -= $value2;
          } elseif ($optionrate2 === "percentage") {
            $rateplan['fixed_price'] -= ($rateplan['fixed_price'] * $value2 / 100);
          }
        }

        // Pastikan fixed_price tidak negatif
        $rateplan['fixed_price'] = max(0, $rateplan['fixed_price']);
        break;
      }
    }

    if (!$found) {
      // Jika rateplan tidak ditemukan, tambahkan baru
      $newPrice = $datarateplan ? $datarateplan['fixed_price'] : 0;

      if ($optionrate1 === "set") {
        $newPrice = $value2;
      } elseif ($optionrate1 === "increase") {
        if ($optionrate2 === "amount") {
          $newPrice += $value2;
        } elseif ($optionrate2 === "percentage") {
          $newPrice += ($newPrice * $value2 / 100);
        }
      } elseif ($optionrate1 === "decrease") {
        if ($optionrate2 === "amount") {
          $newPrice -= $value2;
        } elseif ($optionrate2 === "percentage") {
          $newPrice -= ($newPrice * $value2 / 100);
        }
      }

      $rateplans[] = [
      'rateplan' => $rateplan_id,
      'fixed_price' => max(0, $newPrice),
      ];
    }

    return $rateplans;
  }



";s:5:"title";s:10:"Allocation";s:3:"url";s:11:"/allocation";s:6:"layout";s:9:"Dashboard";s:9:"is_hidden";s:1:"0";s:7:"session";a:3:{s:8:"security";s:4:"user";s:17:"allowedUserGroups";a:2:{i:0;s:5:"admin";i:1;s:8:"supplier";}s:8:"redirect";s:15:"dashboard/login";}}}