<?php
require_once __DIR__ . '/../../config/session.php';
requireAdmin();
require_once __DIR__ . '/../../config/config.php';
require_once __DIR__ . '/../../functions/helper.php';

$db = getDB();

$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';

$where = "WHERE 1=1";
$params = [];

if ($search) {
    $where .= " AND (ih.nama_lengkap LIKE ? OR ih.nik LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
}
if ($status) {
    $where .= " AND ih.status = ?";
    $params[] = $status;
}

$limit = 10;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

$countStmt = $db->prepare("SELECT COUNT(*) FROM ibu_hamil ih $where");
$countStmt->execute($params);
$total_rows = $countStmt->fetchColumn();
$total_pages = ceil($total_rows / $limit);

$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 ORDER BY ih.created_at DESC LIMIT $limit OFFSET $offset");
$stmt->execute($params);
$ibu_hamil = $stmt->fetchAll();
?>
<?php require_once '../../includes/header_admin.php'; ?>

<div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-6">
    <div>
        <h1 class="text-2xl font-bold text-gray-800">Data Ibu Hamil</h1>
        <p class="text-gray-500 text-sm mt-1">Manajemen data kehamilan, HPL, dan identitas ibu hamil.</p>
    </div>
    <div>
        <a href="tambah" class="inline-flex items-center justify-center px-4 py-2 bg-primary hover:bg-primary-dark text-white font-medium rounded-lg transition-colors shadow-sm focus:ring-2 focus:ring-offset-2 focus:ring-primary">
            <i class="fas fa-plus mr-2"></i> Tambah Data Baru
        </a>
    </div>
</div>

<div class="bg-white rounded-2xl shadow-sm border border-gray-100 overflow-hidden mb-6">
    <div class="p-6 border-b border-gray-100 bg-gray-50/50">
        <form method="GET" class="flex flex-col md:flex-row gap-4">
            <div class="flex-grow">
                <div class="relative">
                    <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                        <i class="fas fa-search text-gray-400"></i>
                    </div>
                    <input type="text" name="search" value="<?= escape($search) ?>" class="pl-10 w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-sm" placeholder="Cari Nama / NIK...">
                </div>
            </div>
            <div class="md:w-48">
                <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary focus:border-primary text-sm bg-white">
                    <option value="">Semua Status</option>
                    <option value="Aktif" <?= $status == 'Aktif' ? 'selected' : '' ?>>Aktif</option>
                    <option value="Melahirkan" <?= $status == 'Melahirkan' ? 'selected' : '' ?>>Melahirkan</option>
                    <option value="Keguguran" <?= $status == 'Keguguran' ? 'selected' : '' ?>>Keguguran</option>
                    <option value="Pindah" <?= $status == 'Pindah' ? 'selected' : '' ?>>Pindah</option>
                </select>
            </div>
            <div>
                <button type="submit" class="w-full md:w-auto px-6 py-2 bg-gray-800 hover:bg-gray-900 text-white font-medium rounded-lg text-sm transition-colors">
                    Filter
                </button>
            </div>
            <?php if($search || $status): ?>
                <div>
                    <a href="./" class="w-full md:w-auto px-4 py-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-medium rounded-lg text-sm transition-colors inline-flex justify-center items-center">
                        Reset
                    </a>
                </div>
            <?php endif; ?>
        </form>
    </div>
    
    <!-- Desktop Table -->
    <div class="hidden md:block overflow-x-auto">
        <table class="w-full text-sm text-left whitespace-nowrap">
            <thead class="text-xs text-gray-500 uppercase bg-gray-50 border-b border-gray-100">
                <tr>
                    <th class="px-6 py-4 font-semibold">No</th>
                    <th class="px-6 py-4 font-semibold">Nama / NIK</th>
                    <th class="px-6 py-4 font-semibold text-center">Usia / Trimester</th>
                    <th class="px-6 py-4 font-semibold text-center">HPL</th>
                    <th class="px-6 py-4 font-semibold text-center">Perkiraan</th>
                    <th class="px-6 py-4 font-semibold text-center">Status</th>
                    <th class="px-6 py-4 font-semibold text-center">Aksi</th>
                </tr>
            </thead>
            <tbody class="divide-y divide-gray-100">
                <?php if (count($ibu_hamil) > 0): ?>
                    <?php $no = 1; foreach ($ibu_hamil as $row): ?>
                        <?php 
                            $diff = (new DateTime($row['hpht']))->diff(new DateTime())->days;
                            $minggu = intdiv($diff, 7);
                            $trimester = getTrimester($minggu);
                            $hpl_date = new DateTime($row['hpl']);
                            $today = new DateTime();
                            $is_overdue = $hpl_date < $today;
                            $days_to_hpl = $today->diff($hpl_date)->days;
                            
                            $status_color = match($row['status']) {
                                'Aktif' => 'bg-sky-100 text-sky-800 border-sky-200',
                                'Melahirkan' => 'bg-blue-100 text-blue-800 border-blue-200',
                                'Keguguran' => 'bg-red-100 text-red-800 border-red-200',
                                'Pindah' => 'bg-gray-100 text-gray-800 border-gray-200',
                                default => 'bg-gray-100 text-gray-800 border-gray-200'
                            };
                        ?>
                        <tr class="hover:bg-gray-50 transition-colors">
                            <td class="px-6 py-4 text-gray-500"><?= $no++ ?></td>
                            <td class="px-6 py-4">
                                <div class="font-bold text-gray-900"><?= escape($row['nama_lengkap']) ?></div>
                                <div class="text-xs text-gray-500 mt-1"><?= escape($row['nik']) ?></div>
                            </td>
                            <td class="px-6 py-4 text-center">
                                <div class="font-medium text-gray-900"><?= $minggu ?> Minggu</div>
                                <div class="text-xs text-accent font-bold mt-1">Trimester <?= $trimester ?></div>
                            </td>
                            <td class="px-6 py-4 text-center">
                                <div class="font-bold <?= $is_overdue ? 'text-red-500' : 'text-primary' ?>"><?= date('d M Y', strtotime($row['hpl'])) ?></div>
                            </td>
                            <td class="px-6 py-4 text-center">
                                <?php if($is_overdue): ?>
                                    <span class="text-xs font-bold text-red-500">Melewati HPL</span>
                                <?php else: ?>
                                    <span class="font-semibold text-gray-900"><?= $days_to_hpl ?></span> <span class="text-xs text-gray-500">hari lagi</span>
                                <?php endif; ?>
                            </td>
                            <td class="px-6 py-4 text-center">
                                <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-bold border <?= $status_color ?>">
                                    <?= escape($row['status']) ?>
                                </span>
                            </td>
                            <td class="px-6 py-4 text-center space-x-1">
                                <a href="detail.php?id=<?= $row['id'] ?>" class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-600 hover:text-white transition-colors" title="Detail">
                                    <i class="fas fa-eye"></i>
                                </a>
                                <a href="edit.php?id=<?= $row['id'] ?>" class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-yellow-50 text-yellow-600 hover:bg-yellow-500 hover:text-white transition-colors" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </a>
                                <form action="hapus" method="POST" class="inline-block" onsubmit="return confirm('Yakin ingin menghapus data ini beserta akun pengguna yang terkait?');">
                                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                                    <input type="hidden" name="id" value="<?= $row['id'] ?>">
                                    <button type="submit" class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-red-50 text-red-600 hover:bg-red-600 hover:text-white transition-colors" title="Hapus">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="7" class="px-6 py-12 text-center text-gray-500">
                            <i class="fas fa-inbox text-4xl mb-3 text-gray-300 block"></i>
                            Tidak ada data ibu hamil yang ditemukan.
                        </td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <!-- Mobile Cards -->
    <div class="md:hidden divide-y divide-gray-100">
        <?php if (count($ibu_hamil) > 0): ?>
            <?php foreach ($ibu_hamil as $row): ?>
                <?php 
                    $diff = (new DateTime($row['hpht']))->diff(new DateTime())->days;
                    $minggu = intdiv($diff, 7);
                    $trimester = getTrimester($minggu);
                    $hpl_date = new DateTime($row['hpl']);
                    $today = new DateTime();
                    $is_overdue = $hpl_date < $today;
                    $days_to_hpl = $today->diff($hpl_date)->days;
                    
                    $status_color = match($row['status']) {
                        'Aktif' => 'bg-sky-100 text-sky-800 border-sky-200',
                        'Melahirkan' => 'bg-blue-100 text-blue-800 border-blue-200',
                        'Keguguran' => 'bg-red-100 text-red-800 border-red-200',
                        'Pindah' => 'bg-gray-100 text-gray-800 border-gray-200',
                        default => 'bg-gray-100 text-gray-800 border-gray-200'
                    };
                ?>
                <div class="p-4 hover:bg-gray-50 transition-colors">
                    <div class="flex items-start justify-between mb-3">
                        <div>
                            <div class="font-bold text-gray-900"><?= escape($row['nama_lengkap']) ?></div>
                            <div class="text-xs text-gray-500 font-mono mt-0.5"><?= escape($row['nik']) ?></div>
                        </div>
                        <span class="inline-flex items-center px-2 py-0.5 rounded-full text-[10px] font-bold border <?= $status_color ?>">
                            <?= escape($row['status']) ?>
                        </span>
                    </div>
                    <div class="grid grid-cols-3 gap-2 text-center">
                        <div class="bg-gray-50 rounded-lg p-2">
                            <p class="text-[10px] text-gray-500 uppercase font-semibold">Usia</p>
                            <p class="text-sm font-bold text-gray-900"><?= $minggu ?> <span class="text-xs font-normal text-gray-500">mgg</span></p>
                            <p class="text-[10px] text-accent font-bold">Tri <?= $trimester ?></p>
                        </div>
                        <div class="bg-gray-50 rounded-lg p-2">
                            <p class="text-[10px] text-gray-500 uppercase font-semibold">HPL</p>
                            <p class="text-xs font-bold <?= $is_overdue ? 'text-red-500' : 'text-primary' ?>"><?= date('d M Y', strtotime($row['hpl'])) ?></p>
                        </div>
                        <div class="bg-gray-50 rounded-lg p-2">
                            <p class="text-[10px] text-gray-500 uppercase font-semibold">Perkiraan</p>
                            <?php if($is_overdue): ?>
                                <p class="text-xs font-bold text-red-500">Lewati HPL</p>
                            <?php else: ?>
                                <p class="text-sm font-bold text-gray-900"><?= $days_to_hpl ?> <span class="text-xs font-normal text-gray-500">hari</span></p>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="flex gap-1 mt-3 justify-end">
                        <a href="detail.php?id=<?= $row['id'] ?>" class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-blue-50 text-blue-600 hover:bg-blue-600 hover:text-white transition-colors" title="Detail">
                            <i class="fas fa-eye"></i>
                        </a>
                        <a href="edit.php?id=<?= $row['id'] ?>" class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-yellow-50 text-yellow-600 hover:bg-yellow-500 hover:text-white transition-colors" title="Edit">
                            <i class="fas fa-edit"></i>
                        </a>
                        <form action="hapus" method="POST" class="inline-block" onsubmit="return confirm('Yakin ingin menghapus data ini beserta akun pengguna yang terkait?');">
                            <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                            <input type="hidden" name="id" value="<?= $row['id'] ?>">
                            <button type="submit" class="inline-flex items-center justify-center w-8 h-8 rounded-lg bg-red-50 text-red-600 hover:bg-red-600 hover:text-white transition-colors" title="Hapus">
                                <i class="fas fa-trash"></i>
                            </button>
                        </form>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="px-6 py-12 text-center text-gray-500">
                <i class="fas fa-inbox text-4xl mb-3 text-gray-300 block"></i>
                Tidak ada data ibu hamil yang ditemukan.
            </div>
        <?php endif; ?>
    </div>

    <?= renderPagination($total_pages, $page, './', $_GET) ?>
</div>

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