 <!-- Main content -->
<section class="content">
  <div class="container-fluid">
    <div class="row">
      <div class="col-12">
        <div class="card">
          <div class="card-header">
            <div class="row">
              <div class="col-sm-6">
                <h3 class="card-title">Agen Voucher Pascabayar</h3>
              </div>
              <div class="col-sm-6">
                <ol class="float-sm-right mb-0">
                  <a type="button" class="btn btn-danger btn-sm m-1" data-toggle="modal" data-target="#staticBackdrop">Tambah</a>
                </ol>
              </div>
              <!-- Modal Tambah -->
              <div class="modal fade" id="staticBackdrop" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                <div class="modal-dialog modal-xl">
                  <div class="modal-content">
                    <form method="post" enctype="multipart/form-data">
                      <div class="modal-header bg-primary">
                        <h5 class="modal-title" id="staticBackdropLabel">Tambah Agen</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                          <span aria-hidden="true">&times;</span>
                        </button>
                      </div>
                      <div class="modal-body">
                        <div class="row">
                          <div class="card-body pb-0">
                            <div class="row">
                              <div class="col-md-6">
                                <div class="form-group">
                                  <label>Server</label>
                                  <select class="form-control" name="ids" required="required">
                                    <option value="">Pilih</option>
                                    <?php 
                                    $List = new Listdata();
                                    $List->set_list("data_server",$SqlDataWH);
                                    foreach ($List->get_list() as $key => $value): ?>
                                    <option value="<?php echo $value['id']; ?>" ><?php echo $value['nama_server']; ?></option>
                                    <?php endforeach ?>
                                  </select>
                                </div>
                                <div class="form-group">
                                  <label>Mikrotik</label>
                                  <select class="form-control" name="idm" required="required">
                                    <option value="">Pilih</option>
                                    <?php 
                                    $List = new Listdata();
                                    $List->set_list("setting_mikrotik",$SqlDataWHId);
                                    foreach ($List->get_list() as $key => $value): ?>
                                    <option value="<?php echo $value['id']; ?>" ><?php echo $value['nama']; ?></option>
                                    <?php endforeach ?>
                                  </select>
                                </div>
                                <div class="form-group">
                                  <label>Nama Agen</label>
                                  <input type="text" class="form-control" name="nama" required="required">
                                </div>
                                <div class="form-group">
                                  <label>Nomor Whatsapp</label>
                                  <input type="text" class="form-control" name="nomor" required="required">
                                </div>
                              </div>
                              <div class="col-md-6">
                                <div class="form-group">
                                  <label>Email Agen</label>
                                  <input type="email" class="form-control" name="email" required="required">
                                </div>
                                <div class="form-group">
                                  <label>Kode Agen</label>
                                  <input type="text" class="form-control" name="kode" required="required">
                                </div>
                                <div class="form-group">
                                  <label>Alamat</label>
                                  <textarea class="form-control" rows="4" name="alamat" required="required"></textarea>
                                </div>
                              </div>
                            </div>
                            <a class="btn btn-link" data-toggle="collapse" data-target="#collapseExample" aria-expanded="false" aria-controls="collapseExample">
                                Option Form Tambahan
                            </a>
                            <div class="collapse" id="collapseExample">
                                <div class="card-body">
                                  <label>Pilih Voucher Agen</label>
                                  <div class="row">
                                    <?php 
                                    $List->set_list("profile_paket", $SqlDataWHId. "AND status = '1'");
                                      foreach ($List->get_list() as $key => $value): 
                                        //Kumpulkan semua ID
                                        $ids_menu[] = $value['id'];
                                        ?>
                                      <div class="col-md-4">
                                        <div class="form-check mb-2">
                                          <input class="form-check-input" type="checkbox" value="<?php echo $value['id']; ?>" name="menu_ids[]" id="flexCheckDefault" checked>
                                          <label class="form-check-label" for="flexCheckDefault">
                                              <?php echo $value['nama'] . " ( Rp. ".number_format($value['harga_paket'])." )"; ?>
                                          </label>
                                        </div>
                                      </div>
                                    <?php endforeach ?>
                                  </div>
                                </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <input type="submit" name="tambah" class="btn btn-primary" value="Tambah">
                      </div>
                    </form>
<?php
if (isset($_POST['tambah'])) {

  $difference = array_diff($ids_menu, $_POST['menu_ids']);

  if (empty($difference)) {
    $paket_list = NULL;
  } else {
    $paket_list = implode(', ', $_POST['menu_ids']);
  }

    // Format nomor WhatsApp
    if (substr($_POST['nomor'], 0, 2) == '62') {
        $handphone = $_POST['nomor'];
    } else {
        $handphone = '62' . substr($_POST['nomor'], 1);
    }

    // Cek apakah nomor WhatsApp sudah terdaftar
    $stmt = $pdo->prepare("SELECT nomor_whatsapp FROM agen_voucher WHERE nomor_whatsapp = :NoWhatsApp");
    $stmt->execute([':NoWhatsApp' => $handphone]);
    $ceknomor = $stmt->fetch(PDO::FETCH_ASSOC);

    if (empty($ceknomor)) {
        try {
            // Generate password dan hash
            $password = $_POST['kode'] . date('is');
            $hashedPassword = password_hash($password, PASSWORD_DEFAULT);

            // Insert data agen baru
            $stmt = $pdo->prepare("INSERT INTO agen_voucher (id_data_server, id_setting_mikrotik, email, nama, alamat, nomor_whatsapp, kode_agen, status, profile, password, jenis_agen,list_paket) VALUES (:id_data_server, :id_setting_mikrotik, :email, :nama, :alamat, :nomor_whatsapp, :kode_agen, 'Aktif', 'member.png', :password, 'Prabayar', :list_paket)");

            $stmt->execute([
                ':id_data_server' => $_POST['ids'],
                ':id_setting_mikrotik' => $_POST['idm'],
                ':email' => $_POST['email'],
                ':nama' => $_POST['nama'],
                ':alamat' => $_POST['alamat'],
                ':nomor_whatsapp' => $handphone,
                ':kode_agen' => $_POST['kode'],
                ':password' => $hashedPassword,
                ':list_paket' => $paket_list
            ]);
//Kirim Pesan Registrasi Agen
$Pesan = "*Registrasi Agen Voucher*

Nama      : ".$_POST['nama']."
Alamat    : ".$_POST['alamat']."
Kode Agen : ".$_POST['kode']."
Password  : ".$password."

_Registrasi Berhasil..!!_

_==> Pesan Otomatis Sistem <==_";
$Nomor = array($handphone);
$APIwa = new PesanWA();
$APIwa->Send_Pesan($_POST['ids'],'sendMessage',$Nomor,$Pesan);

            sweetAlert("Agen telah ditambahkan", "success");
        } catch (PDOException $e) {
            sweetAlert("Terjadi kesalahan: " . $e->getMessage(), "error");
        }
    } else {
        sweetAlert("Registrasi Gagal.!, Nomor WhatsApp sudah terdaftar", "error");
    }
}
?>

                  </div>
                </div>
              </div>
              <!-- END Modal Tambah -->
            </div>
          </div>
          <!-- /.card-header -->
          <div class="card-body">
            <table id="example3" class="table table-bordered table-striped">
              <thead>
              <tr>
                <th>No</th>
                <th>Nama Server</th>
                <th>Mikrotik</th>
                <th>Nama Agen</th>
                <th>Kode Agen</th>
                <th>Nomor WhatsApp</th>
                <th>Saldo</th>
                <th>Status</th>
                <th>Action</th>
              </tr>
              </thead>
              <tbody>
              <?php
                $no = 1;
                $aserver = mysqli_query($con,"SELECT * FROM v_detail_agen_voucher $SqlDataWHId AND jenis_agen = 'Prabayar'");
                while ($server = mysqli_fetch_assoc($aserver)) 
                {
              ?>
              <tr>
                <td style="max-width: 30px;"><?php echo $no; ?></td>
                <td><?php echo $server['nama_server']; ?></td>
                <td><?php echo $server['nama_mikrotik']; ?></td>
                <td><?php echo $server['nama']; ?></td>
                <td><?php echo $server['kode_agen']; ?></td>
                <td><?php echo $server['nomor_whatsapp']; ?></td>
                <td style="max-width: 100px;">Rp. <?php echo number_format($server['saldo']); ?></td>
                <td>
                  <?php 
                    if($server['status'] == 'Aktif') {
                      echo '<div class="badge badge-success p-2">Aktif</div>';
                    } else {
                      echo '<div class="badge badge-danger p-2">Tidak Aktif</div>';
                    }
                  ?>
                </td>
                <td>
                  <form method="post">
                    <a href="?<?php echo encrypt_url('agen_voucher_detail|'.$server['id']); ?>" class="btn btn-info btn-sm m-1">Detail</a>
                    <a type="button" class="btn btn-secondary btn-sm ml-1" data-toggle="modal" data-target="#modal-edit<?php echo $server['id'];?>">Edit</a>
                    <input type="submit" name="hapus<?php echo $server['id'];?>" value="Hapus" class="btn btn-danger btn-sm ml-1" />
                  </form>
                </td>
              </tr>
              <!-- Modal Edit -->
              <div class="modal fade" id="modal-edit<?php echo $server['id'];?>" data-backdrop="static" data-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
                <div class="modal-dialog modal-xl">
                  <div class="modal-content">
                    <form method="post" enctype="multipart/form-data">
                      <div class="modal-header bg-secondary">
                        <h5 class="modal-title" id="staticBackdropLabel">Edit Agen Voucher</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                          <span aria-hidden="true">&times;</span>
                        </button>
                      </div>
                      <div class="modal-body">
                        <div class="row">
                          <div class="card-body pb-0">
                            <div class="row">
                              <div class="col-md-6">
                                <div class="form-group">
                                  <label>Server</label>
                                  <select class="form-control" name="ids" required="required">
                                    <option value="">Pilih</option>
                                    <?php 
                                    $List = new Listdata();
                                    $List->set_list("data_server",$SqlDataWH);
                                    foreach ($List->get_list() as $key => $value): ?>
                                    <option value="<?php echo $value['id']; ?>" <?php if($value['id'] == $server['id_data_server']) { echo "selected";} ?> ><?php echo $value['nama_server']; ?></option>
                                    <?php endforeach ?>
                                  </select>
                                </div>
                                <div class="form-group">
                                  <label>Mikrotik</label>
                                  <select class="form-control" name="idm" required="required">
                                    <option value="">Pilih</option>
                                    <?php 
                                    $List = new Listdata();
                                    $List->set_list("setting_mikrotik",$SqlDataWHId);
                                    foreach ($List->get_list() as $key => $value): ?>
                                    <option value="<?php echo $value['id']; ?>" <?php if($value['id'] == $server['id_setting_mikrotik']) { echo "selected";} ?> ><?php echo $value['nama']; ?></option>
                                    <?php endforeach ?>
                                  </select>
                                </div>
                                <div class="form-group">
                                  <label>Nama Agen</label>
                                  <input type="text" class="form-control" name="nama" required="required" value="<?php echo $server['nama']; ?>">
                                </div>
                                <div class="form-group">
                                  <label>Nomor Whatsapp</label>
                                  <input type="text" class="form-control" name="nomor" required="required" value="<?php echo $server['nomor_whatsapp']; ?>">
                                </div>
                              </div>
                              <div class="col-md-6">
                                <div class="form-group">
                                  <label>Email Agen</label>
                                  <input type="email" class="form-control" name="email" required="required" value="<?php echo $server['email']; ?>">
                                </div>
                                <div class="form-group">
                                  <label>Kode Agen</label>
                                  <input type="text" class="form-control" name="kode" required="required" value="<?php echo $server['kode_agen']; ?>">
                                </div>
                                <div class="form-group">
                                  <label>Alamat</label>
                                  <textarea class="form-control" rows="4" name="alamat" required="required"><?php echo $server['alamat']; ?></textarea>
                                </div>
                              </div>
                            </div>
                            <a class="btn btn-link" data-toggle="collapse" data-target="#collapseExample<?php echo $server['id'];?>" aria-expanded="false" aria-controls="collapseExample<?php echo $server['id'];?>">
                                Option Form Tambahan
                            </a>
                            <div class="collapse" id="collapseExample<?php echo $server['id'];?>">
                                <div class="card-body">
                                  <label>Pilih Voucher Agen</label>
                                  <div class="row">
                                    <?php 
                                    $data_paket = explode(",", $server['list_paket']);
                                    $List->set_list("profile_paket", $SqlDataWHId . " AND status = '1'");
                                    $ids_menu = [];

                                    foreach ($List->get_list() as $key => $value): 
                                        // Kumpulkan semua ID
                                        $ids_menu[] = $value['id'];
                                        if (empty($data_paket[0])) {
                                          $checked = 'checked';
                                        } else {
                                        // Cek apakah ID ada dalam array data_paket
                                          $checked = in_array($value['id'], $data_paket) ? 'checked' : ''; // Memperbaiki typo 'cekcked' menjadi 'checked'
                                        }
                                        ?>
                                        <div class="col-md-4">
                                            <div class="form-check mb-2">
                                                <input class="form-check-input" type="checkbox" value="<?php echo $value['id']; ?>" name="menu_ids[]" id="flexCheck<?php echo $value['id']; ?>" <?php echo $checked; ?>>
                                                <label class="form-check-label" for="flexCheck<?php echo $value['id']; ?>">
                                                    <?php echo $value['nama'] . " ( Rp. " . number_format($value['harga_paket']) . " )"; ?>
                                                </label>
                                            </div>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                              </div>
                            </div>
                          </div>
                        </div>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                        <input type="submit" name="edit<?php echo $server['id']; ?>" class="btn btn-warning" value="Edit">
                      </div>
                    </form>
                    <?php
                    if (isset($_POST['edit'.$server['id']])) 
                    {
                      $difference = array_diff($ids_menu, $_POST['menu_ids']);

                        if (empty($difference)) {
                          $paket_list = NULL;
                        } else {
                          $paket_list = implode(', ', $_POST['menu_ids']);
                        }

                      $update = mysqli_query($con,"UPDATE agen_voucher SET 
                        id_data_server      ='$_POST[ids]',
                        id_setting_mikrotik ='$_POST[idm]',
                        email               ='$_POST[email]',
                        nama                ='$_POST[nama]',
                        alamat              ='$_POST[alamat]',
                        nomor_whatsapp      ='$_POST[nomor]',
                        kode_agen           ='$_POST[kode]',
                        list_paket          ='$paket_list'
                        WHERE id            = '$server[id]' ");
                      if ($update) 
                      {
                        sweetAlert("Data agen telah di ubah", "success");
                      }
                    }
                    if (isset($_POST['hapus'.$server['id']]))
                    {
                      $iddata = $server['id'];
                      deleteAlert("agen_voucher",$iddata );
                    }
                    ?>
                </div>
              </div>
              <!-- END Modal Edit -->
            <?php $no++; } ?>
              </tbody>
            </table>
          </div>
          <!-- /.card-body -->
        </div>
        <!-- /.card -->
      </div>
      <!-- /.col -->
    </div>
    <!-- /.row -->
  </div>
  <!-- /.container-fluid -->
</section>
<!-- /.content -->