<?php
require_once __DIR__ . '/../config/session.php';
requireLogin();
if($_SESSION['role'] !== 'user') {
    header('Location: ' . BASE_URL . '/admin/profil');
    exit;
}
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../functions/helper.php';
require_once __DIR__ . '/../functions/csrf.php';

$db = getDB();
$ibu_hamil_id = $_SESSION['ibu_hamil_id'] ?? 0;

if (!$ibu_hamil_id) {
    $stmt = $db->prepare("SELECT ibu_hamil_id FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $ibu_hamil_id = $stmt->fetchColumn() ?: 0;
    if ($ibu_hamil_id) {
        $_SESSION['ibu_hamil_id'] = $ibu_hamil_id;
    } else {
        // Auto-link: cari data ibu_hamil berdasarkan NIK (username)
        $stmt = $db->prepare("SELECT u.username, ih.id FROM users u LEFT JOIN ibu_hamil ih ON u.username = ih.nik WHERE u.id = ?");
        $stmt->execute([$_SESSION['user_id']]);
        $link = $stmt->fetch();
        if ($link && $link['id']) {
            $ibu_hamil_id = $link['id'];
            $stmt = $db->prepare("UPDATE users SET ibu_hamil_id = ? WHERE id = ?");
            $stmt->execute([$ibu_hamil_id, $_SESSION['user_id']]);
            $_SESSION['ibu_hamil_id'] = $ibu_hamil_id;
        }
    }
}

$stmt = $db->prepare("SELECT ih.*, u.nama_lengkap as nama_bidan FROM ibu_hamil ih LEFT JOIN users u ON ih.bidan_id = u.id WHERE ih.id = ?");
$stmt->execute([$ibu_hamil_id]);
$ih = $stmt->fetch();

$umur = $minggu = $trimester = 0;
if ($ih) {
    $dob = new DateTime($ih['tanggal_lahir']);
    $today = new DateTime();
    $umur = $today->diff($dob)->y;
    $diff = (new DateTime($ih['hpht']))->diff(new DateTime())->days;
    $minggu = intdiv($diff, 7);
    $trimester = getTrimester($minggu);
}

// Handle password change
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    $password_lama = $_POST['password_lama'] ?? '';
    $password_baru = $_POST['password_baru'] ?? '';
    $konfirmasi = $_POST['konfirmasi'] ?? '';

    $stmt = $db->prepare("SELECT password FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user = $stmt->fetch();

    if ($password_lama !== $user['password']) {
        setFlash('error', 'Password lama tidak sesuai.');
    } elseif ($password_baru !== $konfirmasi) {
        setFlash('error', 'Konfirmasi password baru tidak cocok.');
    } elseif (strlen($password_baru) < 6) {
        setFlash('error', 'Password baru minimal 6 karakter.');
    } else {
        $stmt = $db->prepare("UPDATE users SET password = ? WHERE id = ?");
        $stmt->execute([$password_baru, $_SESSION['user_id']]);
        setFlash('success', 'Password berhasil diubah.');
    }

    header('Location: profil');
    exit;
}
?>
<?php require_once '../includes/header_user.php'; ?>

<div>
    <div class="mb-8 flex flex-col sm:flex-row sm:items-center justify-between gap-4 no-print">
        <div>
            <h2 class="text-2xl font-bold text-gray-800">Profil Rekam Medis</h2>
            <p class="text-gray-500">Informasi detail identitas dan data kehamilan Anda.</p>
        </div>
        <?php if ($ih): ?>
        <div class="flex items-center gap-2 shrink-0">
            <a href="export_profil.php" target="_blank"
               class="inline-flex items-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white font-medium rounded-lg text-sm transition-colors shadow-sm">
                <i class="fas fa-file-excel"></i> Export Excel
            </a>
            <a href="cetak_profil_pdf.php" target="_blank"
               class="inline-flex items-center gap-2 px-4 py-2 bg-primary hover:bg-primary-dark text-white font-medium rounded-lg text-sm transition-colors shadow-sm">
                <i class="fas fa-file-pdf"></i> Cetak / PDF
            </a>
        </div>
        <?php endif; ?>
    </div>

    <?php if ($ih): ?>
    <!-- Identitas Card -->
    <div class="bg-white rounded-3xl shadow-sm border border-gray-100 overflow-hidden mb-8">
        <div class="px-8 py-6 border-b border-gray-100 flex items-center gap-4 bg-gradient-to-r from-gray-50 to-white">
            <div class="w-12 h-12 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xl">
                <i class="fas fa-address-card"></i>
            </div>
            <div>
                <h3 class="font-bold text-gray-800 text-xl">Identitas Pribadi</h3>
                <p class="text-sm text-gray-500">Data diri sesuai KTP dan tempat tinggal</p>
            </div>
        </div>
        <div class="p-8">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                <div>
                    <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-1">NIK</p>
                    <p class="font-medium text-gray-900 text-lg"><?= escape($ih['nik']) ?></p>
                </div>
                <div>
                    <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-1">Nama Lengkap</p>
                    <p class="font-medium text-gray-900 text-lg"><?= escape($ih['nama_lengkap']) ?></p>
                </div>
                <div>
                    <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-1">Tanggal Lahir & Umur</p>
                    <p class="font-medium text-gray-900"><?= formatDate($ih['tanggal_lahir']) ?> <span class="text-gray-500 bg-gray-100 px-2 py-0.5 rounded-md ml-1 text-sm"><?= $umur ?> Tahun</span></p>
                </div>
                <div>
                    <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-1">Golongan Darah</p>
                    <span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-bold bg-red-50 text-red-600 border border-red-100">
                        <?= escape($ih['golongan_darah']) ?>
                    </span>
                </div>
                <div class="md:col-span-2">
                    <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-1">Alamat Lengkap</p>
                    <div class="bg-gray-50 border border-gray-100 rounded-xl p-4">
                        <p class="font-medium text-gray-800"><?= escape($ih['alamat']) ?></p>
                    </div>
                </div>
                <div>
                    <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-1">No. HP / WhatsApp</p>
                    <p class="font-medium text-gray-900 flex items-center gap-2">
                        <i class="fab fa-whatsapp text-sky-500"></i> <?= escape($ih['no_hp']) ?>
                    </p>
                </div>
                <div>
                    <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-1">Suami & Kontak</p>
                    <p class="font-medium text-gray-900"><?= escape($ih['nama_suami']) ?> <span class="text-gray-500 text-sm">(<?= escape($ih['no_hp_suami'] ?: '-') ?>)</span></p>
                </div>
            </div>
        </div>
    </div>

    <!-- Kehamilan Card -->
    <div class="bg-white rounded-3xl shadow-sm border border-gray-100 overflow-hidden mb-8 relative">
        <div class="absolute top-0 right-0 w-32 h-32 bg-primary/5 rounded-bl-full pointer-events-none"></div>
        <div class="px-8 py-6 border-b border-gray-100 flex items-center gap-4 bg-gradient-to-r from-gray-50 to-white">
            <div class="w-12 h-12 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xl">
                <i class="fas fa-stethoscope"></i>
            </div>
            <div>
                <h3 class="font-bold text-gray-800 text-xl">Informasi Kehamilan</h3>
                <p class="text-sm text-gray-500">Data medis dan perkiraan kelahiran</p>
            </div>
        </div>
        <div class="p-8 relative z-10">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
                <!-- Left Side -->
                <div class="space-y-6">
                    <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                        <span class="text-sm font-bold text-gray-400 uppercase tracking-widest">Kehamilan Ke-</span>
                        <span class="text-xl font-black text-gray-800"><?= escape($ih['kehamilan_ke']) ?></span>
                    </div>
                    <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                        <span class="text-sm font-bold text-gray-400 uppercase tracking-widest">HPHT</span>
                        <span class="font-medium text-gray-800 bg-gray-50 px-3 py-1 rounded-lg"><?= formatDate($ih['hpht']) ?></span>
                    </div>
                    <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                        <span class="text-sm font-bold text-gray-400 uppercase tracking-widest">Usia Kehamilan</span>
                        <span class="font-bold text-primary text-lg"><?= $minggu ?> Minggu</span>
                    </div>
                    <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                        <span class="text-sm font-bold text-gray-400 uppercase tracking-widest">Trimester</span>
                        <span class="font-bold text-primary px-3 py-1 bg-primary/10 rounded-lg">Trimester <?= $trimester ?></span>
                    </div>
                </div>
                
                <!-- Right Side -->
                <div class="space-y-6">
                    <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                        <span class="text-sm font-bold text-gray-400 uppercase tracking-widest">Perkiraan Lahir</span>
                        <span class="font-black text-red-500 text-lg"><?= formatDate($ih['hpl']) ?></span>
                    </div>
                    <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                        <span class="text-sm font-bold text-gray-400 uppercase tracking-widest">Status</span>
                        <span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-bold bg-sky-50 text-sky-700 border border-sky-200 uppercase tracking-wider">
                            <?= escape($ih['status']) ?>
                        </span>
                    </div>
                    <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                        <span class="text-sm font-bold text-gray-400 uppercase tracking-widest">Bidan PJ</span>
                        <span class="font-medium text-gray-800 flex items-center gap-2"><i class="fas fa-user-nurse text-primary/50"></i> <?= escape($ih['nama_bidan']) ?></span>
                    </div>
                    <div class="flex items-center justify-between border-b border-gray-100 pb-3">
                        <span class="text-sm font-bold text-gray-400 uppercase tracking-widest">Terdaftar Sejak</span>
                        <span class="font-medium text-gray-500 text-sm"><?= formatDate($ih['tanggal_daftar']) ?></span>
                    </div>
                </div>
                
                <?php if($ih['catatan']): ?>
                    <div class="md:col-span-2 mt-4">
                        <p class="text-xs font-bold text-gray-400 uppercase tracking-widest mb-3">Catatan Khusus dari Bidan</p>
                        <div class="bg-yellow-50/80 border border-yellow-200 rounded-2xl p-5 text-sm text-yellow-800 leading-relaxed shadow-inner">
                            <i class="fas fa-quote-left text-yellow-300 text-2xl float-left mr-3 mb-2"></i>
                            <?= nl2br(escape($ih['catatan'])) ?>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <?php else: ?>
    <div class="bg-yellow-50 border-l-4 border-yellow-500 p-6 rounded-r-xl shadow-sm mb-8">
        <div class="flex items-start gap-3">
            <i class="fas fa-exclamation-triangle text-yellow-500 text-xl mt-0.5"></i>
            <div>
                <h3 class="font-bold text-yellow-800 text-lg mb-1">Data Belum Tersedia</h3>
                <p class="text-yellow-700 text-sm">Data rekam medis kehamilan Anda belum terhubung dengan akun ini. Silakan hubungi admin Posyandu untuk proses sinkronisasi data.</p>
            </div>
        </div>
    </div>
    <?php endif; ?>

    <!-- Ubah Password Card -->
    <div class="bg-white rounded-3xl shadow-sm border border-gray-100 overflow-hidden mb-8 no-print">
        <div class="px-8 py-6 border-b border-gray-100 flex items-center gap-4 bg-gradient-to-r from-gray-50 to-white">
            <div class="w-12 h-12 rounded-full bg-purple-100 text-purple-600 flex items-center justify-center text-xl">
                <i class="fas fa-lock"></i>
            </div>
            <div>
                <h3 class="font-bold text-gray-800 text-xl">Ubah Password</h3>
                <p class="text-sm text-gray-500">Perbarui kata sandi Anda untuk menjaga keamanan akun</p>
            </div>
        </div>
        <div class="p-8 relative z-10">
            <form action="profil" method="POST" class="space-y-6">
                <?= csrfField() ?>
                
                <div x-data="{ show: false }">
                    <label class="block text-sm font-bold text-gray-700 uppercase tracking-wider mb-2">Password Lama <span class="text-red-500">*</span></label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                            <i class="fas fa-unlock-alt text-gray-400"></i>
                        </div>
                        <input :type="show ? 'text' : 'password'" name="password_lama" class="w-full pl-11 pr-12 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm bg-gray-50 focus:bg-white transition-colors" required placeholder="Masukkan password saat ini">
                        <button type="button" @click="show = !show" class="absolute inset-y-0 right-0 pr-4 flex items-center text-gray-400 hover:text-gray-600 focus:outline-none">
                            <i class="fas" :class="show ? 'fa-eye-slash' : 'fa-eye'"></i>
                        </button>
                    </div>
                </div>
                
                <hr class="border-gray-100 my-6">
                
                <div x-data="{ show: false }">
                    <label class="block text-sm font-bold text-gray-700 uppercase tracking-wider mb-2">Password Baru <span class="text-red-500">*</span></label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                            <i class="fas fa-key text-gray-400"></i>
                        </div>
                        <input :type="show ? 'text' : 'password'" name="password_baru" class="w-full pl-11 pr-12 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm bg-gray-50 focus:bg-white transition-colors" required minlength="6" placeholder="Minimal 6 karakter">
                        <button type="button" @click="show = !show" class="absolute inset-y-0 right-0 pr-4 flex items-center text-gray-400 hover:text-gray-600 focus:outline-none">
                            <i class="fas" :class="show ? 'fa-eye-slash' : 'fa-eye'"></i>
                        </button>
                    </div>
                </div>
                
                <div x-data="{ show: false }">
                    <label class="block text-sm font-bold text-gray-700 uppercase tracking-wider mb-2">Konfirmasi Password Baru <span class="text-red-500">*</span></label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-4 flex items-center pointer-events-none">
                            <i class="fas fa-check-double text-gray-400"></i>
                        </div>
                        <input :type="show ? 'text' : 'password'" name="konfirmasi" class="w-full pl-11 pr-12 py-3 border border-gray-300 rounded-xl focus:ring-2 focus:ring-purple-500 focus:border-purple-500 text-sm bg-gray-50 focus:bg-white transition-colors" required minlength="6" placeholder="Ketik ulang password baru">
                        <button type="button" @click="show = !show" class="absolute inset-y-0 right-0 pr-4 flex items-center text-gray-400 hover:text-gray-600 focus:outline-none">
                            <i class="fas" :class="show ? 'fa-eye-slash' : 'fa-eye'"></i>
                        </button>
                    </div>
                </div>
                
                <div class="pt-2">
                    <button type="submit" class="w-full md:w-auto py-3.5 px-8 bg-purple-600 hover:bg-purple-700 text-white font-bold rounded-xl shadow-lg shadow-purple-600/30 transition-all transform hover:-translate-y-0.5 focus:ring-2 focus:ring-offset-2 focus:ring-purple-600 flex items-center justify-center gap-2">
                        <i class="fas fa-save"></i> Simpan Password Baru
                    </button>
                </div>
            </form>
        </div>
    </div>

    <div class="text-center text-sm text-gray-500 mb-12 flex flex-col items-center gap-2 no-print">
        <i class="fas fa-info-circle text-gray-400 text-xl"></i>
        <p>Jika terdapat kesalahan data, mohon segera hubungi <strong class="text-gray-700">Bidan Penanggungjawab</strong> atau Admin Posyandu untuk dilakukan perubahan.</p>
    </div>
</div>

<style>
@media print {
    /* Sembunyikan elemen UI */
    .no-print, nav, header, aside,
    [class*="sidebar"], [class*="topbar"],
    #sidebar, #topbar {
        display: none !important;
    }
    /* Reset layout ke full width */
    body { background: #fff !important; }
    main, .flex-1, [class*="overflow-y-auto"] {
        overflow: visible !important;
        width: 100% !important;
        padding: 0 !important;
        margin: 0 !important;
    }
    /* Kartu lebih sederhana saat print */
    .rounded-3xl, .rounded-2xl, .rounded-xl {
        border-radius: 4px !important;
        box-shadow: none !important;
    }
    /* Header print posyandu */
    .print-header { display: block !important; }
}
.print-header { display: none; }
</style>

<!-- Header khusus print -->
<div class="print-header" style="text-align:center;padding:12px 0 16px;border-bottom:2px solid #333;margin-bottom:16px;">
    <h2 style="font-size:16pt;font-weight:bold;margin:0;"><?= escape($profil_web['nama_posyandu'] ?? APP_NAME) ?></h2>
    <p style="font-size:9pt;color:#555;margin:4px 0 0;">Rekam Medis Ibu Hamil &mdash; Dicetak: <?= date('d/m/Y H:i') ?></p>
</div>

<?php require_once '../includes/footer_user.php'; ?>
