<?php
session_start();
include 'db.php';

if (!isset($_SESSION['username'])) {
    header("Location: index.php");
    exit;
}

$result = $conn->query("SELECT * FROM pelanggan");
?>

<html>
<head>
<title>Daftar Pelanggan</title>
<style>
body {
  font-family: Verdana, Arial;
  background: linear-gradient(135deg, #f5f7fa, #c3cfe2);
  margin: 0;
  padding: 20px;
}
h2 {
  text-align: center;
  color: #333;
}
table {
  border-collapse: collapse;
  width: 90%;
  margin: 20px auto;
  background-color: #fff;
  box-shadow: 0 0 10px rgba(0,0,0,0.1);
  border-radius: 10px;
  overflow: hidden;
}
th {
  background-color: #004aad;
  color: white;
  padding: 12px;
  text-align: center;
}
td {
  border-bottom: 1px solid #ddd;
  padding: 10px;
  text-align: center;
}
tr:hover {
  background-color: #f1f1f1;
}
button {
  background-color: #28a745;
  border: none;
  color: white;
  padding: 10px 20px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
}
button:hover {
  background-color: #218838;
}
.container {
  text-align: center;
}
</style>
</head>

<body>
<h2>📋 Daftar Pelanggan</h2>

<div class="container">
  <button onclick="exportTableToExcel('pelanggan')">Export ke Excel</button>
</div>

<table id="pelanggan">
  <tr>
    <th>Nama Pelanggan</th>
    <th>Alamat</th>
    <th>Email</th>
    <th>Nomor Ponsel</th>
  </tr>

<?php
while ($row = $result->fetch_assoc()) {
    echo "<tr>";
    echo "<td>" . htmlspecialchars($row['Nama']) . "</td>";
    echo "<td>" . htmlspecialchars($row['Alamat']) . "</td>";
    echo "<td>" . htmlspecialchars($row['Email']) . "</td>";
    echo "<td>" . htmlspecialchars($row['No_hape']) . "</td>";
    echo "</tr>";
}
$conn->close();
?>
</table>

<script>
// Fungsi sederhana export ke Excel
function exportTableToExcel(tableID, filename = ''){
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
    filename = filename ? filename + '.xls' : 'data_pelanggan.xls';
    var downloadLink = document.createElement("a");
    document.body.appendChild(downloadLink);
    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHTML], { type: dataType });
        navigator.msSaveOrOpenBlob( blob, filename);
    } else {
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
        downloadLink.download = filename;
        downloadLink.click();
    }
}
</script>

</body>
</html>
