<?php
// Ensure session is started at the very beginning
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Include configuration and sidebar
require '../config.php';
require '../admin/sidebar.php'; // Ensure this path is correct based on your file structure

// --- PHP Logic Enhancements ---

// Process deletion if POST request with 'hapus_id'
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['hapus_id'])) {
    $hapus_id = (int) $_POST['hapus_id']; // Cast to int for safety

    // Use prepared statement for secure deletion
    $stmt_delete = $conn->prepare("DELETE FROM pengguna WHERE id = ? AND peran = 'pelanggan'");
    if ($stmt_delete === false) {
        // Handle error, e.g., log it or display a message
        $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Gagal menyiapkan query hapus: ' . $conn->error];
        header("Location: data_pelanggan.php");
        exit;
    }
    $stmt_delete->bind_param("i", $hapus_id); // "i" for integer type
    if ($stmt_delete->execute()) {
        if ($stmt_delete->affected_rows > 0) {
            $_SESSION['alert'] = ['type' => 'success', 'message' => 'Data pelanggan berhasil dihapus.'];
        } else {
            $_SESSION['alert'] = ['type' => 'warning', 'message' => 'Pelanggan tidak ditemukan atau bukan peran pelanggan.'];
        }
    } else {
        $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Gagal menghapus data pelanggan: ' . $stmt_delete->error];
    }
    $stmt_delete->close(); // Close the statement
    header("Location: data_pelanggan.php"); // Redirect after POST to prevent re-submission
    exit;
}

// Fetch all customer data (pelanggan) using prepared statement
$stmt_pelanggan = $conn->prepare("SELECT * FROM pengguna WHERE peran = 'pelanggan'");
if ($stmt_pelanggan === false) {
    die("Prepare failed for pelanggan query: " . $conn->error);
}
$stmt_pelanggan->execute();
$result_pelanggan = $stmt_pelanggan->get_result();

?>

<!DOCTYPE html>
<html lang="id">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data Pelanggan - Admin </title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        /* This styling ensures content fills the area beside the sidebar */
        body {
            /* This is defined in sidebar.php, ensuring overall layout */
            /* min-height: 100vh;
            display: flex; */
            background-color: #f4f7f6;
            /* Light gray background for consistency */
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            color: #333;
        }

        /* Content wrapper styles from produk.php to ensure consistent page layout */
        #page-content-wrapper {
            flex-grow: 1;
            padding: 30px;
            background-color: #ffffff;
            /* White content background */
            border-radius: 12px;
            /* Softly rounded corners */
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
            /* Subtle shadow */
            margin: 20px;
            /* Margin around the content area */
        }

        .main-header {
            font-size: 2.2rem;
            font-weight: 700;
            color: #2c3e50;
            /* Darker title color */
            margin-bottom: 25px;
            padding-bottom: 15px;
            border-bottom: 2px solid #eee;
            /* Subtle separator */
            text-align: center;
        }

        /* Table Styling */
        .table {
            background-color: #fff;
            border-radius: 10px;
            /* Rounded table corners */
            overflow: hidden;
            /* Ensures radius applies */
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
            /* Very light table shadow */
            margin-top: 20px;
        }

        .table thead th {
            background-color: #ecf0f1;
            /* Light header background */
            color: #555;
            font-weight: 600;
            border-bottom: 1px solid #dee2e6;
            padding: 12px 15px;
            text-transform: uppercase;
            font-size: 0.9em;
        }

        .table tbody tr:hover {
            background-color: #f9f9f9;
            /* Subtle hover effect */
        }

        .table td {
            padding: 12px 15px;
            vertical-align: middle;
            font-size: 0.95em;
        }

        /* Button Styling */
        .btn-info {
            background-color: #3498db;
            /* Flat blue */
            border-color: #3498db;
            color: #fff;
            font-weight: 500;
            border-radius: 6px;
            transition: all 0.2s ease;
        }

        .btn-info:hover {
            background-color: #217dbb;
            border-color: #217dbb;
            color: #fff;
        }

        .btn-danger {
            background-color: #e74c3c;
            /* Flat red */
            border-color: #e74c3c;
            font-weight: 500;
            border-radius: 6px;
            transition: all 0.2s ease;
        }

        .btn-danger:hover {
            background-color: #c0392b;
            border-color: #c0392b;
        }

        /* Alert Styling */
        .alert {
            border-radius: 8px;
            /* Rounded alert corners */
            font-size: 1.05em;
            padding: 15px 20px;
            margin-bottom: 25px;
            /* Space below alert */
        }

        .alert-success {
            background-color: #d4edda;
            color: #155724;
            border-color: #c3e6cb;
        }

        .alert-danger {
            background-color: #f8d7da;
            color: #721c24;
            border-color: #f5c6cb;
        }

        .alert-warning {
            background-color: #fff3cd;
            color: #856404;
            border-color: #ffeeba;
        }

        .alert .btn-close {
            font-size: 0.9em;
        }

        /* Modal Styling */
        .modal-content {
            border-radius: 12px;
            /* Rounded modal corners */
            border: none;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
        }

        .modal-header {
            background-color: #f8f9fa;
            /* Light header */
            border-bottom: 1px solid #e9ecef;
            border-top-left-radius: 12px;
            border-top-right-radius: 12px;
            padding: 20px;
        }

        .modal-header h5 {
            color: #34495e;
            /* Dark title */
            font-weight: 600;
            font-size: 1.5rem;
        }

        .modal-body {
            padding: 25px;
        }

        .modal-footer {
            border-top: 1px solid #e9ecef;
            padding: 15px 25px;
            border-bottom-left-radius: 12px;
            border-bottom-right-radius: 12px;
        }

        .list-group-item {
            border: none;
            /* Remove borders for a cleaner list */
            padding: 10px 0;
            font-size: 0.95em;
        }

        .list-group-item:first-child {
            padding-top: 0;
        }

        .list-group-item:last-child {
            padding-bottom: 0;
        }

        .list-group-item strong {
            display: inline-block;
            min-width: 120px;
            /* Align labels */
            color: #555;
            font-weight: 600;
        }
    </style>
</head>

<body>
    <div id="wrapper">
        <?php // The sidebar.php content is included here 
        ?>
        <div id="page-content-wrapper">
            <div class="container-fluid">
                <?php if (isset($_SESSION['alert'])): ?>
                    <div class="alert alert-<?= $_SESSION['alert']['type'] ?> alert-dismissible fade show" role="alert">
                        <i class="fas fa-info-circle me-2"></i> <?= $_SESSION['alert']['message'] ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['alert']); ?>
                <?php endif; ?>

                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>#</th>
                                <th>Nama</th>
                                <th>Email</th>
                                <th class="text-center">Aksi</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if ($result_pelanggan->num_rows > 0): ?>
                                <?php $no = 1;
                                while ($p = $result_pelanggan->fetch_assoc()): ?>
                                    <tr>
                                        <td><?= $no++ ?></td>
                                        <td><?= htmlspecialchars($p['nama']) ?></td>
                                        <td><?= htmlspecialchars($p['email']) ?></td>
                                        <td class="text-center">
                                            <button class="btn btn-info btn-sm me-2" data-bs-toggle="modal" data-bs-target="#detailModal<?= $p['id'] ?>">
                                                <i class="fas fa-eye"></i> Detail
                                            </button>

                                            <button class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#hapusModal<?= $p['id'] ?>">
                                                <i class="fas fa-trash-alt"></i> Hapus
                                            </button>

                                            <div class="modal fade" id="detailModal<?= $p['id'] ?>" tabindex="-1" aria-labelledby="detailModalLabel<?= $p['id'] ?>" aria-hidden="true">
                                                <div class="modal-dialog modal-dialog-centered">
                                                    <div class="modal-content">
                                                        <div class="modal-header">
                                                            <h5 class="modal-title" id="detailModalLabel<?= $p['id'] ?>">Detail Pelanggan: <?= htmlspecialchars($p['nama']) ?></h5>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                        </div>
                                                        <div class="modal-body">
                                                            <ul class="list-group list-group-flush">
                                                                <li class="list-group-item"><strong>Nama:</strong> <?= htmlspecialchars($p['nama']) ?></li>
                                                                <li class="list-group-item"><strong>Email:</strong> <?= htmlspecialchars($p['email']) ?></li>
                                                                <li class="list-group-item"><strong>Jenis Kelamin:</strong> <?= htmlspecialchars($p['jenis_kelamin'] ?? '-') ?></li>
                                                                <li class="list-group-item"><strong>No Telp:</strong> <?= htmlspecialchars($p['no_telp'] ?? '-') ?></li>
                                                                <li class="list-group-item"><strong>Provinsi:</strong> <?= htmlspecialchars($p['provinsi'] ?? '-') ?></li>
                                                                <li class="list-group-item"><strong>Kab/Kota:</strong> <?= htmlspecialchars($p['kabupaten_kota'] ?? '-') ?></li>
                                                                <li class="list-group-item"><strong>Kecamatan:</strong> <?= htmlspecialchars($p['kecamatan'] ?? '-') ?></li>
                                                                <li class="list-group-item"><strong>Kelurahan:</strong> <?= htmlspecialchars($p['kelurahan'] ?? '-') ?></li>
                                                                <li class="list-group-item"><strong>Alamat Lengkap:</strong> <?= htmlspecialchars($p['alamat_lengkap'] ?? '-') ?></li>
                                                                <li class="list-group-item"><strong>Terdaftar Sejak:</strong> <?= htmlspecialchars($p['dibuat_pada'] ?? '-') ?></li>
                                                            </ul>
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="modal fade" id="hapusModal<?= $p['id'] ?>" tabindex="-1" aria-labelledby="hapusModalLabel<?= $p['id'] ?>" aria-hidden="true">
                                                <div class="modal-dialog modal-dialog-centered">
                                                    <form method="POST" class="modal-content">
                                                        <input type="hidden" name="hapus_id" value="<?= htmlspecialchars($p['id']) ?>">
                                                        <div class="modal-header">
                                                            <h5 class="modal-title" id="hapusModalLabel<?= $p['id'] ?>">Konfirmasi Hapus</h5>
                                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                        </div>
                                                        <div class="modal-body">
                                                            Anda yakin ingin menghapus pelanggan <strong><?= htmlspecialchars($p['nama']) ?></strong>? Tindakan ini tidak dapat dibatalkan.
                                                        </div>
                                                        <div class="modal-footer">
                                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                                                            <button type="submit" class="btn btn-danger"><i class="fas fa-trash-alt me-2"></i>Ya, Hapus</button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="4" class="text-center py-4 text-muted">Tidak ada data pelanggan yang ditemukan.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>

</html>