<?php
session_start();
require_once '../config.php';
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../login.php");
    exit;
}

$success = false;
$id_meteran_baru = '';
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $nama = trim($_POST['nama']);
    $alamat = trim($_POST['alamat']);
    $no_hp = trim($_POST['no_hp']);
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    if (empty($nama) || empty($alamat)) {
        $error = "Nama dan Alamat wajib diisi!";
    } else {
        // 1. Generate ID Meteran Otomatis
        $stmt = $pdo->query("SELECT id_meteran FROM pelanggan ORDER BY id DESC LIMIT 1");
        $last_id = $stmt->fetchColumn();
        $next_num = 1;
        if ($last_id) {
            $num_part = (int)substr($last_id, 4); // Ambil angka setelah "MTR-"
            $next_num = $num_part + 1;
        }
        $id_meteran_baru = "MTR-" . str_pad($next_num, 4, "0", STR_PAD_LEFT);

        // 2. Hash password jika ada
        $hashed_pass = !empty($password) ? password_hash($password, PASSWORD_DEFAULT) : null;

        // 3. Insert ke database
        try {
            $stmt = $pdo->prepare("INSERT INTO pelanggan (id_meteran, nama, alamat, no_hp, username, password, status) VALUES (?, ?, ?, ?, ?, ?, 'aktif')");
            $stmt->execute([$id_meteran_baru, $nama, $alamat, $no_hp, $username, $hashed_pass]);
            $success = true;
        } catch (PDOException $e) {
            $error = "Gagal menyimpan data: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Tambah Pelanggan - SPAM</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<style>
body { background:#f4f7fe; font-family:'Segoe UI'; }
.bg-header{
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color:white;
    padding:18px;
    border-bottom-left-radius:20px;
    border-bottom-right-radius:20px;
}
.form-card {
    background: white;
    border-radius: 20px;
    box-shadow: 0 6px 18px rgba(0,0,0,0.05);
    padding: 20px;
    margin-top: -20px;
}
.form-control {
    border-radius: 12px;
    padding: 12px 15px;
    border: 1px solid #e0e0e0;
    background: #f8f9fa;
}
.form-control:focus {
    border-color: #3A7CA5;
    box-shadow: 0 0 0 0.25rem rgba(58, 124, 165, 0.25);
    background: white;
}
.form-label { font-weight: 700; font-size: 0.85rem; color: #4a5568; }
.btn-sage {
    background: linear-gradient(135deg, #3A7CA5 0%, #2C5F7D 100%);
    color: white;
    border: none;
    border-radius: 12px;
    padding: 12px;
    font-weight: 700;
    width: 100%;
}
.qr-box {
    background: #f8f9fa;
    border-radius: 16px;
    padding: 20px;
    text-align: center;
    border: 2px dashed #3A7CA5;
}
.qr-box img { max-width: 200px; height: auto; }
@media print {
    body * { visibility: hidden; }
    #printArea, #printArea * { visibility: visible; }
    #printArea { position: absolute; left: 0; top: 0; width: 100%; }
}
</style>
</head>
<body>

<div class="bg-header shadow-sm">
    <div class="container d-flex justify-content-between align-items-center">
        <a href="manajemen_pelanggan.php" class="text-white"><i class="fa fa-arrow-left"></i></a>
        <h5 class="mb-0 fw-bold">Tambah Pelanggan</h5>
        <div style="width: 20px;"></div>
    </div>
</div>

<div class="container pb-5">
    <?php if ($success): ?>
        <!-- Tampilan Sukses & QR Code -->
        <div id="printArea" class="form-card text-center">
            <div class="text-success mb-3"><i class="fa fa-check-circle fa-3x"></i></div>
            <h5 class="fw-bold">Pelanggan Berhasil Ditambahkan!</h5>
            <p class="text-muted small">Silakan cetak barcode ini dan tempelkan pada meteran air pelanggan.</p>
            
            <div class="qr-box mb-3">
                <h4 class="fw-bold text-sage mb-2"><?= htmlspecialchars($id_meteran_baru) ?></h4>
                <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=<?= urlencode($id_meteran_baru) ?>" alt="QR Code">
                <p class="small text-muted mt-2 mb-0"><?= htmlspecialchars($nama) ?></p>
                <p class="small text-muted"><?= htmlspecialchars($alamat) ?></p>
            </div>
            
            <button onclick="window.print()" class="btn btn-sage mb-2"><i class="fa fa-print me-2"></i> Cetak Barcode</button>
            <a href="tambah_pelanggan.php" class="btn btn-outline-secondary w-100" style="border-radius:12px;">Tambah Lagi</a>
        </div>
    <?php else: ?>
        <!-- Form Input -->
        <div class="form-card">
            <?php if ($error): ?>
                <div class="alert alert-danger" style="font-size:0.85rem; border-radius:10px;"><?= $error ?></div>
            <?php endif; ?>

            <form method="POST">
                <div class="mb-3">
                    <label class="form-label">Nama Pelanggan</label>
                    <input type="text" name="nama" class="form-control" required placeholder="Nama lengkap pemilik meteran">
                </div>
                <div class="mb-3">
                    <label class="form-label">Alamat Lengkap</label>
                    <textarea name="alamat" class="form-control" rows="2" required placeholder="RT/RW, Dusun, Desa"></textarea>
                </div>
                <div class="mb-3">
                    <label class="form-label">Nomor HP / WhatsApp</label>
                    <input type="text" name="no_hp" class="form-control" placeholder="08xxxxxxxxxx (Untuk kirim tagihan)">
                </div>
                
                <hr class="my-4">
                <p class="small text-muted mb-2"><i class="fa fa-info-circle me-1"></i> Opsional: Buat akun login untuk pelanggan</p>
                
                <div class="mb-3">
                    <label class="form-label">Username Pelanggan</label>
                    <input type="text" name="username" class="form-control" placeholder="Kosongkan jika tidak perlu login">
                </div>
                <div class="mb-4">
                    <label class="form-label">Password Pelanggan</label>
                    <input type="password" name="password" class="form-control" placeholder="Minimal 6 karakter">
                </div>

                <button type="submit" class="btn btn-sage">
                    <i class="fa fa-save me-2"></i> Simpan & Generate ID Meteran
                </button>
            </form>
        </div>
    <?php endif; ?>
</div>

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