<?php

session_start();

// Cek apakah user sudah login
if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    // Jika belum login, redirect ke halaman login
    header("Location: login.php");
    exit();
}

// koneksi ke database
// error_reporting(0);
include 'connection.php';

// Mendapatkan data dealer untuk dropdown
$dealer_query = "SELECT name_dealer, code_dealer FROM dealer";
$dealer_result = $conn->query($dealer_query);

// Mendapatkan data bulan untuk dropdown
$bulan_query = "SELECT bulan FROM api_service_ach_vw2 GROUP BY bulan";
$bulan_result = $conn->query($bulan_query);

// Mendapatkan data tahun untuk dropdown
$tahun_query = "SELECT tahun FROM api_service_ach_vw2 GROUP BY tahun";
$tahun_result = $conn->query($tahun_query);
?>

<!DOCTYPE html>
<html lang="en">
<?php
include 'head.php';
?>

<body>

<?php
include 'header.php';
?>



<?php
$activeMenu = 'achievement'; // Sesuaikan dengan halaman yang sedang dibuka
include 'sidebar.php';
?>



  <main id="main" class="main">

    <div class="pagetitle">
      <h1>Achievement</h1>
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item"><a href="index.html">Home</a></li>
          <li class="breadcrumb-item active">Achievement</li>
        </ol>
      </nav>
    </div><!-- End Page Title -->

    <section class="section dashboard">
      <div class="row">

        <!-- Left side columns -->
        <div class="col-lg-12">
          <div class="row">

            <!-- Filter Tujuan Dealer -->
            <div class="col-12">
              <div class="card recent-sales overflow-auto">

                <div class="card-body">
                  <h5 class="card-title">Filter Tujuan Dealer</h5>

                  <form method="POST" action="" class="row g-3 align-items-end">
                    <div class="col-md-6">
                      <label for="dealer" class="form-label">Dealer</label>
                      <select name="dealer_code" id="dealer" class="form-control select2">
                        <option value="" disabled selected hidden>Pilih Dealer</option>
                        <?php
                        if ($dealer_result->num_rows > 0) {
                          while ($dealer = $dealer_result->fetch_assoc()) {
                        ?>
                            <option value="<?php echo "$dealer[code_dealer]" ?>"
                              <?php if (isset($_POST['dealer_code']) && $_POST['dealer_code'] == $dealer['code_dealer']) { ?>selected="" <?php } ?>>
                              <?php echo htmlspecialchars($dealer['name_dealer']) ?></option>
                        <?php
                          }
                        }
                        ?>
                      </select>
                    </div>

                    <div class="col-md-2">
                      <label for="bulan" class="form-label">Bulan</label>
                      <select name="bulan" id="bulan" class="form-control">
                        <option value="" disabled selected hidden>Pilih Bulan</option>
                        <?php
                        if ($bulan_result->num_rows > 0) {
                          while ($bulan = $bulan_result->fetch_assoc()) {
                        ?>
                            <option value="<?php echo "$bulan[bulan]" ?>"
                              <?php if (isset($_POST['bulan']) && $_POST['bulan'] == $bulan['bulan']) { ?>selected="" <?php } ?>>
                              <?php echo htmlspecialchars($bulan['bulan']) ?></option>
                        <?php
                          }
                        }
                        ?>
                      </select>
                    </div>

                    <div class="col-md-2">
                      <label for="tahun" class="form-label">Tahun</label>
                      <select name="tahun" id="tahun" class="form-control">
                        <option value="" disabled selected hidden>Pilih Tahun</option>
                        <?php
                        if ($tahun_result->num_rows > 0) {
                          while ($tahun = $tahun_result->fetch_assoc()) {
                        ?>
                            <option value="<?php echo "$tahun[tahun]" ?>"
                              <?php if (isset($_POST['tahun']) && $_POST['tahun'] == $tahun['tahun']) { ?>selected="" <?php } ?>>
                              <?php echo htmlspecialchars($tahun['tahun']) ?></option>
                        <?php
                          }
                        }
                        ?>
                      </select>
                    </div>

                    <div class="col-md-2 d-flex justify-content-end">
                      <button type="submit" class="btn btn-primary mt-3 w-100">Tampilkan</button>
                    </div>
                  </form><!-- End Custom Styled Validation with Tooltips -->

                </div>

              </div>
            </div><!-- End Filter Tujuan Dealer -->

            <!-- Table -->
            <div class="col-12">
              <div class="card recent-sales">

                <div class="card-body">



                  <?php
                  // Menangani form submission
                  if ($_SERVER["REQUEST_METHOD"] == "POST") {
                    $site_id = $_POST['dealer_code'];
                    $bulan = $_POST['bulan'];
                    $tahun = $_POST['tahun'];

                    // Validasi input
                    if (empty($site_id) || empty($bulan) || empty($tahun)) {
                      echo "<br><div class='alert alert-danger'>Pastikan anda memilih Dealer, Bulan, dan Tahun.</div>";
                    } else {

                      // Cek apakah kombinasi bulan & tahun sudah ada di target_service_dealer
                      $check_query = "SELECT * FROM target_service_dealer WHERE bulan = '$bulan' AND tahun = '$tahun'";
                      $check_result = $conn->QUERY($check_query);

                      IF ($check_result->num_rows == 0) {
                          // Jika belum ada, isi otomatis target_service dengan DATA dari api_service_ach_vw2
                          $insert_query = "INSERT INTO target_service (site_id, name_dealer, bulan, tahun)
                                          SELECT site_id, name_dealer, '$bulan', '$tahun' FROM api_service_ach_vw2
                                          WHERE bulan = '$bulan' AND tahun = '$tahun'
                                          GROUP BY site_id, bulan, tahun";
                          IF ($conn->QUERY($insert_query) === TRUE) {
                              echo "<br><div class='alert alert-success'>Data Target bulan ini telah terisi Otomatis.</div>";
                          } else {
                              echo "<br><div class='alert alert-danger'>Gagal mengisi Data Target bulan ini: " . $conn->error . "</div>";
                          }
                      }



                      // Query untuk mengambil data berdasarkan site_id, bulan, dan tahun
                      $sql = "SELECT *
                          FROM api_service_ach_vw2
                          WHERE site_id = '$site_id' AND bulan = '$bulan' AND tahun = '$tahun'";

                      // echo $sql; // Debugging: menampilkan query

                      $result = $conn->query($sql);

                      if ($result->num_rows > 0) {
                        // Query untuk mengambil nama dealer secara terpisah
                        $sql_name = "SELECT *
                              FROM api_service_ach_vw2
                              WHERE site_id = '$site_id' AND bulan = '$bulan' AND tahun = '$tahun' LIMIT 1";
                        $result_name = $conn->query($sql_name);

                        if ($result_name->num_rows > 0) {
                          $row_name = $result_name->fetch_assoc();
                          $name_dealer = $row_name['name_dealer'];
                          $bulan = $row_name['bulan'];
                          $tahun = $row_name['tahun'];
                        } else {
                          $name_dealer = "Nama dealer tidak ditemukan";
                        }
                  ?>
                        <!-- Display Dealer and Period -->

                        <div class="row">
                          <div class="col-md-12 d-flex justify-content-between">

                            <div class="col-md-3">

                              <!-- Button untuk membuka modal -->
                              <button type="button" class="btn btn-outline-info mt-3 w-100" data-bs-toggle="modal" data-bs-target="#targetDealerModal"
                                onclick="loadTargetDealer('<?php echo $site_id; ?>', '<?php echo $name_dealer; ?>', '<?php echo $bulan; ?>', '<?php echo $tahun; ?>')">
                                Target Dealer
                              </button>

                            </div>

                            <!-- <div class="col-md-3">
                              <button type="submit" class="btn btn-outline-success mt-3 w-100"><i class="uil uil-file-export"></i> Export</button>
                            </div> -->
                          </div>
                        </div>
                        <div class="overflow-auto">
                          <h3 class="card-title text-center mt-1 mb-1"><strong>LAPORAN OMZET MEKANIK</strong> </h3>
                          <h3 class="card-title text-center mb-3"><strong>Periode : <?php echo " $bulan/$tahun"; ?><br><br><?php echo $name_dealer; ?></strong> </h3>

                          <table class='table table-hover table-bordered text-center'>
                            <thead class="thead-light align-middle">
                              <tr>
                                <th rowspan="2">No</th>
                                <th rowspan="2" width="200px">Nama Teknisi</th>
                                <th rowspan="2">Unit</th>
                                <th colspan="5">Pendapatan</th>
                                <th colspan="2">%</th>
                                <th rowspan="2">Tarif</th>
                                <th colspan="3">Insentif</th>
                              </tr>
                              <tr>
                                <th>Jasa</th>
                                <th>Sparepart</th>
                                <th>Claim</th>
                                <th><span data-bs-toggle="tooltip" data-bs-placement="top" title="Oli dan Busi">Other</th>
                                <th>Total</th>
                                <th>% Jasa</th>
                                <th>% Part</th>
                                <th>Inc. Jasa</th>
                                <th>Inc. Part</th>
                                <th>Inc. Total</th>
                              </tr>
                            </thead>
                            <tbody>
                              <?php
                              $total_transaksi_all = 0;
                              $total_jasa_all = 0;
                              $total_claim_all = 0;
                              $total_sparepart_all = 0;
                              $total_others_all = 0;
                              $total_all_all = 0;
                              $percen_jasa = 0;
                              $percen_part = 0;
                              $tot_percen_jasa = 0;
                              $tot_percen_part = 0;
                              $tarif = 0.045;
                              $inc_jasa = 0;
                              $total_inc_jasa = 0;
                              $inc_part = 0;
                              $total_inc_part = 0;
                              $inc_total = 0;
                              $total_inc_total = 0;
                              $no = 1; // Inisialisasi nomor

                              while ($row = $result->fetch_assoc()) {
                                $sql_claim = "SELECT *
                                  FROM `service_claim`
                                  WHERE site_id = '$row[site_id]' AND bulan = '$row[bulan]' AND tahun = '$row[tahun]' AND technician_name = '$row[technician_name]'";
                                $result_claim = $conn->query($sql_claim); // Eksekusi query

                                if ($result_claim->num_rows > 0) {
                                  $row_claim = $result_claim->fetch_assoc(); // Ambil hasil
                                  $claim_jasa = $row_claim['total_labor_amount'];
                                  $claim_part = $row_claim['total_part_amount'];
                                  $claim_oli = $row_claim['total_oil_amount'];
                                } else {
                                  $claim_jasa = 0;
                                  $claim_part = 0;
                                  $claim_oli = 0;
                                }

                                $sql_vw3 = "SELECT total_jasa, total_part_amount, total_claim
                                  FROM `api_service_ach_vw3`
                                  WHERE site_id = '$row[site_id]' AND bulan = '$row[bulan]' AND tahun = '$row[tahun]' AND technician_name = '$row[technician_name]'";
                                $result_vw3 = $conn->query($sql_vw3); // Eksekusi query

                                if ($result_vw3->num_rows > 0) {
                                  $row_vw3 = $result_vw3->fetch_assoc(); // Ambil hasil
                                  $total_jasa = $row_vw3['total_jasa'] + $claim_jasa;
                                  $total_part = $row_vw3['total_part_amount'] + $claim_part;
                                  $total_claim = $row_vw3['total_claim'];
                                } else {
                                  $total_jasa = 0; // Jika tidak ada hasil
                                  $total_part = 0;
                                  $total_claim = 0;
                                }

                                $oth_busi = "SELECT *,SUM(jumlah) AS tot
                                  FROM `api_service_ach_vw4`
                                  WHERE site_id = '$row[site_id]' AND bulan = '$row[bulan]' AND tahun = '$row[tahun]' AND technician_name = '$row[technician_name]'";
                                $result_oth_busi = $conn->query($oth_busi); // Eksekusi query
                                $row_oth_busi = $result_oth_busi->fetch_assoc(); // Ambil hasil

                                $oth_oli = "SELECT *,SUM(jumlah) AS tot
                                  FROM `api_service_ach_vw5`
                                  WHERE site_id = '$row[site_id]' AND bulan = '$row[bulan]' AND tahun = '$row[tahun]' AND technician_name = '$row[technician_name]'";
                                $result_oth_oli = $conn->query($oth_oli); // Eksekusi query
                                $row_oth_oli = $result_oth_oli->fetch_assoc(); // Ambil hasil

                                $oth = $row_oth_busi['tot'] + $row_oth_oli['tot'] + $claim_oli;

                                $sparepart = $total_part - $row_oth_busi['tot'];

                                $total_all = $total_jasa + $sparepart + $oth;

                                $target = "SELECT * FROM target_service_dealer WHERE site_id = '$row[site_id]' AND bulan = '$row[bulan]' AND tahun = '$row[tahun]'";
                                $result_target = $conn->query($target); // Eksekusi query
                                $row_target = $result_target->fetch_assoc(); // Ambil hasil

                                // Cek apakah penyebut bukan nol sebelum membagi
                                if ($row_target['total_jasa'] != 0 && $row_target['jml_tech'] != 0) {
                                  $percen_jasa = $total_jasa / ($row_target['total_jasa'] / $row_target['jml_tech']);
                                  $percen_part = ($sparepart + $oth) / ($row_target['part_n_oli'] / $row_target['jml_tech']);
                                } else {
                                  $percen_jasa = 0;
                                  $percen_part = 0;
                                }

                                if ($percen_jasa >= 1) {
                                  $inc_jasa = $tarif * $total_jasa;
                                } else if ($percen_jasa >= 0.9 && $percen_jasa < 1) {
                                  $inc_jasa = $tarif * $total_jasa * 0.5;
                                } else {
                                  $inc_jasa = 0;
                                }

                                if ($percen_part >= 1) {
                                  $inc_part = $tarif * $sparepart;
                                } else if ($percen_part >= 0.9 && $percen_part < 1) {
                                  $inc_part = $tarif * $sparepart * 0.5;
                                } else {
                                  $inc_part = 0;
                                }

                                $inc_total = $inc_jasa + $inc_part;


                                echo "<tr>";
                                echo "<td>" . $no++ . "</td>";
                                echo "<td class=\"text-start\">" . $row['technician_name'] . "</td>";
                                echo "<td>" . number_format($row['total_transaksi'], 0, ',', '.') . "</td>";
                                echo "<td class=\"text-end\">Rp" . number_format($total_jasa, 0, ',', '.') . "</td>";
                                echo "<td class=\"text-end\">Rp" . number_format($sparepart, 0, ',', '.') . "</td>";
                                echo "<td class=\"text-end\">Rp" . number_format($total_claim, 0, ',', '.') . "</td>";
                                echo "<td>Rp" . number_format($oth, 0, ',', '.') . "</td>";
                                echo "<td>Rp" . number_format($total_all, 0, ',', '.') . "</td>";
                                echo "<td>" . number_format($percen_jasa * 100, 1, ',', '.') . "%</td>";
                                echo "<td>" . number_format($percen_part * 100, 1, ',', '.') . "%</td>";
                                echo "<td>" . number_format($tarif * 100, 1, ',', '.') . "</td>";
                                echo "<td>Rp" . number_format($inc_jasa, 0, ',', '.') . "</td>";
                                echo "<td>Rp" . number_format($inc_part, 0, ',', '.') . "</td>";
                                echo "<td>Rp" . number_format($inc_total, 0, ',', '.') . "</td>";
                                echo "</tr>";

                                $total_transaksi_all += $row['total_transaksi'];
                                $total_jasa_all += $total_jasa;
                                $total_sparepart_all += $sparepart;
                                $total_claim_all += $total_claim;
                                $total_others_all += $oth;
                                $total_all_all += $total_all;
                                $total_inc_jasa += $inc_jasa;
                                $total_inc_part += $inc_part;
                                $total_inc_total += $inc_total;
                              }

                              if ($row_target['total_jasa'] != 0 || $row_target['part_n_oli'] != 0) {
                                $tot_percen_jasa = $total_jasa_all / $row_target['total_jasa'];
                                $tot_percen_part = ($total_others_all + $total_all_all) / $row_target['part_n_oli'];
                              } else {
                                $tot_percen_jasa = 0;
                                $tot_percen_part = 0;
                              }


                              echo "<tr>
                                    <td colspan='2' class=\"text-start\"><strong>Total</strong></td>
                                    <td><strong>" . number_format($total_transaksi_all, 0, ',', '.') . "</strong></td>
                                    <td class=\"text-end\"><strong>Rp" . number_format($total_jasa_all, 0, ',', '.') . "</strong></td>
                                    <td class=\"text-end\"><strong>Rp" . number_format($total_sparepart_all, 0, ',', '.') . "</strong></td>
                                    <td class=\"text-end\"><strong>Rp" . number_format($total_claim_all, 0, ',', '.') . "</strong></td>
                                    <td class=\"text-end\"><strong>Rp" . number_format($total_others_all, 0, ',', '.') . "</strong></td>
                                    <td class=\"text-end\"><strong>Rp" . number_format($total_all_all, 0, ',', '.') . "</strong></td>
                                    <td class=\"text-end\"><strong>" . number_format($tot_percen_jasa * 100, 1, ',', '.') . "%</strong></td>
                                    <td class=\"text-end\"><strong>" . number_format($tot_percen_part * 100, 1, ',', '.') . "%</strong></td>
                                    <td></td>
                                    <td class=\"text-end\"><strong>Rp" . number_format($total_inc_jasa, 0, ',', '.') . "</strong></td>
                                    <td class=\"text-end\"><strong>Rp" . number_format($total_inc_part, 0, ',', '.') . "</strong></td>
                                    <td class=\"text-end\"><strong>Rp" . number_format($total_inc_total, 0, ',', '.') . "</strong></td>
                                    </tr>";
                              ?>
                            </tbody>
                          </table>
                        </div>

                    <?php
                      } else {
                        echo "<div class='alert alert-danger mt-4 mb-1'>Tidak ada data yang ditemukan untuk Dealer, Bulan, dan Tahun yang dipilih.</div>";
                      }
                    }
                  } else { ?>
                    <!-- Default Title -->
                    <div class="alert alert-warning text-center mt-4 mb-1" role="alert">
                      <h3 class="card-title">Silahkan Pilih Dealer, Bulan dan Tahun</h3>
                    </div>
                  <?php } ?>

                </div>

              </div>
            </div><!-- End Table -->


          </div>
        </div><!-- End Left side columns -->


      </div>
    </section>

  </main><!-- End #main -->


  <!-- Modal -->
  <div class="modal fade" id="targetDealerModal" tabindex="-1" aria-labelledby="targetDealerModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="targetDealerModalLabel">Target Dealer</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <!-- Konten dari modal akan dimuat di sini melalui AJAX -->
          <div id="modalContent"></div>
        </div>
        <div class="modal-footer">
          <button id="editBtn" type="button" class="btn btn-outline-warning"><i class="uil uil-pen"></i> Edit</button>
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>



  <?php
  include 'footer.php';
  ?>

  <a href="#" class="back-to-top d-flex align-items-center justify-content-center"><i class="bi bi-arrow-up-short"></i></a>

  <!-- Vendor JS Files -->
  <script src="assets/vendor/apexcharts/apexcharts.min.js"></script>
  <script src="assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
  <script src="assets/vendor/chart.js/chart.umd.js"></script>
  <script src="assets/vendor/echarts/echarts.min.js"></script>
  <script src="assets/vendor/quill/quill.js"></script>
  <script src="assets/vendor/simple-datatables/simple-datatables.js"></script>
  <script src="assets/vendor/tinymce/tinymce.min.js"></script>
  <script src="assets/vendor/php-email-form/validate.js"></script>


  <!-- Template Main JS File -->
  <script src="assets/js/main.js"></script>


  <script>
    $(document).ready(function() {
      $('#dealer').select2({
        theme: 'bootstrap-5', // Menggunakan tema Bootstrap 5
        placeholder: "Pilih Dealer",
        allowClear: true
      });
    });

    function loadTargetDealer(dealerCode, nameDealer, bulan, tahun) {
      $.ajax({
        url: 'get_target_dealer_data.php',
        type: 'POST',
        data: {
          dealer_code: dealerCode,
          name_dealer: nameDealer,
          bulan: bulan,
          tahun: tahun
        },
        success: function(response) {
          // Tampilkan data di dalam modal
          $('#modalContent').html(response);
          
          // Update the edit button's href to point to target_dealer_edit.php with the right parameters
          $('#editBtn').click(function() {
            window.location.href = 'target_dealer_edit.php?dealer_code=' + dealerCode +
                                    '&name_dealer=' + nameDealer +
                                    '&bulan=' + bulan +
                                    '&tahun=' + tahun;
          });
        },
        error: function() {
          $('#modalContent').html('<p>Error loading data.</p>');
        }
      });
    }
  </script>

  <!-- <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"></script> -->


</body>

</html>