<?php
$page_title = 'Import Contacts';
require_once('includes/load.php');
$groups = $db->query("SELECT * FROM crm_group_contact");
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['contacts_file']) && $_FILES['contacts_file']['error'] == UPLOAD_ERR_OK) {
  $fileTmpPath = $_FILES['contacts_file']['tmp_name'];
  $fileName = $_FILES['contacts_file']['name'];
  $fileSize = $_FILES['contacts_file']['size'];
  $fileType = $_FILES['contacts_file']['type'];

  // Periksa apakah file yang diunggah adalah CSV
  if (pathinfo($fileName, PATHINFO_EXTENSION) === 'csv') {
    // Buka file untuk dibaca
    if (($handle = fopen($fileTmpPath, 'r')) !== FALSE) {
      // Lewati baris header
      $header = fgetcsv($handle, 0, ';');

      // Tambahkan kolom "Error" di CSV output
      $header[] = "Error";
      $invalidContacts = [];

      // Koneksi database (asumsikan $db sudah didefinisikan)
      $stmt = $db->prepare("INSERT INTO crm_contact (name, phone_number, email) VALUES (?, ?, ?)");

      // Baca setiap baris dari CSV
      while (($data = fgetcsv($handle, 0, ';')) !== FALSE) {
        $name = trim($data[0]);
        $phone_number = trim($data[1]);
        $email = trim($data[2]);

        $error = "";

        // Validasi: Nomor telepon harus diawali dengan 62
        if (!preg_match('/^62[0-9]+$/', $phone_number)) {
          $error = "Nomor telepon tidak valid";
        }

        // Jika ada error, simpan ke array
        if ($error) {
          $data[] = $error;
          $invalidContacts[] = $data;
          continue;
        }

        // Bind dan eksekusi statement
        $stmt->bind_param("sss", $name, $phone_number, $email);
        if (!$stmt->execute()) {
          echo "Error inserting data: " . $stmt->error . "<br>";
        }
      }
      fclose($handle);
      $stmt->close();

      // Jika ada data yang tidak valid, simpan ke CSV
      if (!empty($invalidContacts)) {
        $errorFileName = "errors/invalid_contacts_" . time() . ".csv";
        if (!file_exists('errors')) {
          mkdir('errors', 0777, true);
        }
        $errorFile = fopen($errorFileName, 'w');
        fputcsv($errorFile, $header, ';');

        foreach ($invalidContacts as $invalidRow) {
          fputcsv($errorFile, $invalidRow, ';');
        }
        fclose($errorFile);

        echo "Import selesai dengan beberapa kesalahan. Unduh file error: <a href='$errorFileName' target='_blank'>Download</a>";
      } else {
        echo "Contacts imported successfully!";
      }
    } else {
      echo "Error opening the file.";
    }
  } else {
    echo "Uploaded file is not a CSV.";
  }
}


if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_groups'])) {
  $selected_contacts = $_POST['contact_ids'] ?? [];
  $new_group_id = intval($_POST['new_group_id']);

  // Update the crm_group_contact_id for selected contacts
  if (!empty($selected_contacts)) {
    // Create a comma-separated list of contact IDs
    $contact_ids = implode(',', array_map('intval', $selected_contacts));

    // Update the crm_group_contact_id for selected contacts using IN clause
    $db->query("UPDATE crm_contact SET crm_group_contact_id = $new_group_id WHERE id IN ($contact_ids)");

    echo "<script>alert('Group berhasil diperbarui untuk kontak yang dipilih!');</script>";
    redirect('view-contact.php');
  } else {
    echo "<script>alert('Tidak ada kontak yang dipilih!');</script>";
  }
}

include_once('layouts/header.php'); ?>


<style>
td {
  color: #2c3e50;
}

body {
  background: linear-gradient(to right, #2c3e50, #34495e);
  font-family: Arial, sans-serif;
}

.import-window {
  background-color: #34495e;
  height: 100vh;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
}

.import-header {
  background: linear-gradient(to right, #4caf50, #81c784);
  color: white;
  padding: 10px;
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
}

.import-body {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
}

.contact-list {
  background-color: #2c3e50;
  color: #ecf0f1;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
  margin-top: 20px;
}

.contact-list h3 {
  color: #4caf50;
}

.list-group-item {
  background-color: #34495e;
  color: #ecf0f1;
  border: none;
  border-radius: 5px;
  margin-bottom: 10px;
  transition: background-color 0.3s;
}

.list-group-item:hover {
  background-color: #4caf50;
  color: white;
}

.import-input {
  display: flex;
  padding: 10px;
  background-color: #2c3e50;
  border-radius: 8px;
}

.import-input input[type="file"] {
  flex: 1;
  margin-right: 10px;
  padding: 10px;
  border: none;
  border-radius: 5px;
  background-color: #ecf0f1;
}

.import-input button {
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 15px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.import-input button:hover {
  background-color: #388e3c;
}

.dataTables_wrapper th {
  background-color: #388e3c !important;
}

.contact-list {
  background-color: rgb(196, 237, 199) !important;
  color: #ecf0f1;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.5);
  margin-top: 20px;
}

.contact-list h3 {
  color: #4caf50;
}

.list-group-item {
  background-color: #34495e;
  color: #ecf0f1;
  border: none;
  border-radius: 5px;
  margin-bottom: 10px;
  transition: background-color 0.3s;
}

.list-group-item:hover {
  background-color: #4caf50;
  color: white;
}

.download-template {
  margin-top: 10px;
}

.download-template a {
  background-color: rgb(4, 144, 9);
  color: white;
  padding: 10px 15px;
  border-radius: 5px;
  text-decoration: none;
  transition: background-color 0.3s;
}

.btn-secondary {
  background-color: rgb(4, 144, 9);
  color: white;
  padding: 10px 15px;
  border-radius: 5px;
  text-decoration: none;
  transition: background-color 0.3s;
}

.download-template a:hover {
  background-color: #388e3c;
}
</style>

<div class="container">
  <div class="row">
    <div class="col-md-12 header">
      <h2 class="text-white">Import Contacts</h2>
    </div>
  </div>
  <div class="row">
    <div class="col-md-12 import-window">
      <div class="import-header">
        <h3>Upload Contacts Extension .csv</h3>
      </div>
      <div class="import-body">
        <form action="view-contact.php" method="post" enctype="multipart/form-data">
          <div class="import-input">
            <input type="file" name="contacts_file" accept=".csv" required>
            <button type="submit">Import</button>
          </div>
          <div class="download-template">
            <a href="assets\template-contact.csv" class="btn btn-secondary" download>Download Template</a>
          </div>
        </form>
        <div class="contact-list">
          <h3>Existing Contacts</h3>
          <form method="POST" action="view-contact.php">
            <div class="form-group">
              <select name="new_group_id" class="form-control" required>
                <option value="">Pilih Group</option>
                <?php foreach ($groups as $group): ?>
                <option value="<?php echo $group['id']; ?>"><?php echo htmlspecialchars($group['name']); ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <table id="contactsTable" class="display">
              <thead>
                <tr>
                  <th class="" style="width: 50px;">
                    <input type="checkbox" id="checkAll">
                  </th>
                  <th>Name</th>
                  <th>Group Name</th>
                  <th>Phone Number</th>
                  <th>Email</th>
                  <th>Is Template</th>
                </tr>
              </thead>
              <tbody>
                <?php
                // Fetch contacts from the database
                $result = $db->query("SELECT cc.*, COALESCE(cgc.name, '-') as 'group_name' FROM crm_contact cc left join crm_group_contact cgc on cc.crm_group_contact_id = cgc.id where not cc.id = 1");
                while ($contact = $result->fetch_assoc()) {
                  echo "<tr>
                        <td><input type='checkbox' name='contact_ids[]' class='item-checkbox' value='{$contact['id']}'></td>
                        <td>{$contact['name']}</td>
                        <td>{$contact['group_name']}</td>
                        <td>{$contact['phone_number']}</td>
                        <td>{$contact['email']}</td>
                        <td>" . ($contact['is_template'] ? 'Yes' : 'No') . "</td>
                    </tr>";
                }
                ?>
              </tbody>
            </table>

            <button type="submit" name="update_groups" class="btn btn-secondary mt-3">Update Group</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</div>
<script>
$(document).ready(function() {
  var table = $('#contactsTable').DataTable({
    "paging": true,
    "searching": true,
    "ordering": true,
    "info": true,
    "lengthChange": true,
    "pageLength": 20
  });
  $('#checkAll').on('change', function() {
    const isChecked = this.checked;
    // Select/Deselect all checkboxes in the DataTable
    table.$('.item-checkbox').prop('checked', isChecked);
  });
});
</script>
<?php include_once('layouts/footer.php'); ?>