<?php
/**
 * Anggota (Members) Management
 * Koperasi Management System
 */

$pageTitle = 'Anggota';
$pageSubtitle = 'Kelola data anggota koperasi';

require_once __DIR__ . '/config/database.php';
$db = getDB();

// ── Ensure foto column exists ─────────────────────────────────────────────────
try {
    $db->exec("ALTER TABLE anggota ADD COLUMN IF NOT EXISTS foto VARCHAR(255) DEFAULT NULL");
} catch (Exception $e) { /* column may already exist */ }

// ── Ensure is_konsumsi column exists ─────────────────────────────────────────
try {
    $db->exec("ALTER TABLE anggota ADD COLUMN IF NOT EXISTS is_konsumsi TINYINT(1) DEFAULT 1");
} catch (Exception $e) { /* column may already exist */ }

define('FOTO_ANGGOTA_DIR', __DIR__ . '/uploads/anggota/');
define('FOTO_ANGGOTA_URL', 'uploads/anggota/');

// Handle Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';

    if ($action === 'add') {
        $no_anggota = generateNumber('AGT', 'anggota', 'no_anggota');
        
        $foto = null;
        if (isset($_FILES['foto']) && $_FILES['foto']['error'] === 0) {
            $file = $_FILES['foto'];
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $allowedExts = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'svg', 'tiff'];
            $maxSize = 5 * 1024 * 1024; // 5MB
            if (in_array($ext, $allowedExts) && $file['size'] <= $maxSize) {
                $filename = 'anggota_' . time() . '_' . uniqid() . '.' . $ext;
                if (!is_dir(FOTO_ANGGOTA_DIR)) {
                    mkdir(FOTO_ANGGOTA_DIR, 0755, true);
                }
                if (move_uploaded_file($file['tmp_name'], FOTO_ANGGOTA_DIR . $filename)) {
                    $foto = $filename;
                }
            }
        }

        $stmt = $db->prepare("INSERT INTO anggota (no_anggota, nama, nik, tempat_lahir, tanggal_lahir, jenis_kelamin, alamat, telepon, email, pekerjaan, tanggal_daftar, is_konsumsi, foto) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            $no_anggota,
            sanitize($_POST['nama']),
            sanitize($_POST['nik'] ?? ''),
            sanitize($_POST['tempat_lahir'] ?? ''),
            $_POST['tanggal_lahir'] ?: null,
            $_POST['jenis_kelamin'] ?? 'L',
            sanitize($_POST['alamat'] ?? ''),
            sanitize($_POST['telepon'] ?? ''),
            sanitize($_POST['email'] ?? ''),
            sanitize($_POST['pekerjaan'] ?? ''),
            $_POST['tanggal_daftar'] ?: date('Y-m-d'),
            isset($_POST['is_konsumsi']) ? 1 : 0,
            $foto
        ]);
        
        // Auto-create simpanan pokok
        $anggotaId = $db->lastInsertId();
        $simpPokok = getSetting('simpanan_pokok', 100000);
        $stmtSimp = $db->prepare("INSERT INTO simpanan (anggota_id, jenis, tipe, jumlah, tanggal, keterangan, created_by) VALUES (?, 'pokok', 'setoran', ?, ?, 'Simpanan pokok pendaftaran', ?)");
        $stmtSimp->execute([$anggotaId, $simpPokok, $_POST['tanggal_daftar'] ?: date('Y-m-d'), $_SESSION['user_id']]);
        
        setFlash('success', "Anggota $no_anggota berhasil ditambahkan.");
        header('Location: anggota.php');
        exit;
    }
    
    if ($action === 'edit') {
        $id = $_POST['id'];
        $foto = $_POST['old_foto'] ?? '';

        if (isset($_FILES['foto']) && $_FILES['foto']['error'] === 0) {
            $file = $_FILES['foto'];
            $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
            $allowedExts = ['jpg', 'jpeg', 'png', 'webp', 'gif', 'bmp', 'svg', 'tiff'];
            $maxSize = 5 * 1024 * 1024; // 5MB
            if (in_array($ext, $allowedExts) && $file['size'] <= $maxSize) {
                $filename = 'anggota_' . $id . '_' . time() . '.' . $ext;
                if (!is_dir(FOTO_ANGGOTA_DIR)) {
                    mkdir(FOTO_ANGGOTA_DIR, 0755, true);
                }
                if (move_uploaded_file($file['tmp_name'], FOTO_ANGGOTA_DIR . $filename)) {
                    // Delete old photo
                    if ($foto && file_exists(FOTO_ANGGOTA_DIR . $foto)) {
                        unlink(FOTO_ANGGOTA_DIR . $foto);
                    }
                    $foto = $filename;
                }
            }
        }

        $stmt = $db->prepare("UPDATE anggota SET nama=?, nik=?, tempat_lahir=?, tanggal_lahir=?, jenis_kelamin=?, alamat=?, telepon=?, email=?, pekerjaan=?, status=?, is_konsumsi=?, foto=? WHERE id=?");
        $stmt->execute([
            sanitize($_POST['nama']),
            sanitize($_POST['nik'] ?? ''),
            sanitize($_POST['tempat_lahir'] ?? ''),
            $_POST['tanggal_lahir'] ?: null,
            $_POST['jenis_kelamin'] ?? 'L',
            sanitize($_POST['alamat'] ?? ''),
            sanitize($_POST['telepon'] ?? ''),
            sanitize($_POST['email'] ?? ''),
            sanitize($_POST['pekerjaan'] ?? ''),
            $_POST['status'] ?? 'aktif',
            isset($_POST['is_konsumsi']) ? 1 : 0,
            $foto ?: null,
            $id
        ]);
        setFlash('success', 'Data anggota berhasil diperbarui.');
        header('Location: anggota.php');
        exit;
    }
    
    if ($action === 'delete') {
        // Also delete foto file
        $oldStmt = $db->prepare("SELECT foto FROM anggota WHERE id = ?");
        $oldStmt->execute([$_POST['id']]);
        $oldFoto = $oldStmt->fetchColumn();
        if ($oldFoto && file_exists(FOTO_ANGGOTA_DIR . $oldFoto)) {
            unlink(FOTO_ANGGOTA_DIR . $oldFoto);
        }
        $stmt = $db->prepare("DELETE FROM anggota WHERE id = ?");
        $stmt->execute([$_POST['id']]);
        setFlash('success', 'Anggota berhasil dihapus.');
        header('Location: anggota.php');
        exit;
    }
}

// Search & Filter
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 10;
$offset = ($page - 1) * $perPage;

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

if ($search) {
    $where .= " AND (nama LIKE ? OR no_anggota LIKE ? OR telepon LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

if ($status) {
    $where .= " AND status = ?";
    $params[] = $status;
}

$countStmt = $db->prepare("SELECT COUNT(*) FROM anggota $where");
$countStmt->execute($params);
$totalRows = $countStmt->fetchColumn();
$totalPages = ceil($totalRows / $perPage);

$stmt = $db->prepare("SELECT * FROM anggota $where ORDER BY created_at DESC LIMIT $perPage OFFSET $offset");
$stmt->execute($params);
$anggotaList = $stmt->fetchAll();

// For edit modal - get single member if requested
$editData = null;
if (isset($_GET['edit'])) {
    $editStmt = $db->prepare("SELECT * FROM anggota WHERE id = ?");
    $editStmt->execute([$_GET['edit']]);
    $editData = $editStmt->fetch();
}

include __DIR__ . '/includes/header.php';
?>

<!-- Toolbar -->
<div class="card">
    <div class="card-header">
        <div class="toolbar" style="width: 100%;">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" id="searchInput" placeholder="Cari nama, no anggota..." 
                       value="<?= htmlspecialchars($search) ?>"
                       onkeydown="if(event.key==='Enter') { window.location='anggota.php?search='+this.value; }">
            </div>
            <div class="filter-group">
                <select onchange="window.location='anggota.php?status='+this.value+'&search=<?= urlencode($search) ?>'">
                    <option value="">Semua Status</option>
                    <option value="aktif" <?= $status === 'aktif' ? 'selected' : '' ?>>Aktif</option>
                    <option value="nonaktif" <?= $status === 'nonaktif' ? 'selected' : '' ?>>Nonaktif</option>
                </select>
            </div>
            <div style="margin-left: auto; display: flex; gap: 10px;">
                <a href="imports/import_anggota_excel.php" class="btn btn-outline">
                    <i class="fas fa-file-import"></i> Import
                </a>
                <a href="export_anggota.php" class="btn btn-success">
                    <i class="fas fa-file-export"></i> Export
                </a>
                <button class="btn btn-primary" onclick="openModal('addModal')">
                    <i class="fas fa-plus"></i> Tambah Anggota
                </button>
            </div>
        </div>
    </div>

    <div class="table-responsive">
        <table class="data-table" id="anggotaTable">
            <thead>
                <tr>
                    <th>Anggota</th>
                    <th>NIK</th>
                    <th>Telepon</th>
                    <th>Pekerjaan</th>
                    <th>Tanggal Daftar</th>
                    <th>Status</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($anggotaList)): ?>
                    <tr><td colspan="7" class="text-center text-muted" style="padding: 40px;">
                        <i class="fas fa-users" style="font-size: 2rem; display: block; margin-bottom: 10px; color: var(--gray-300);"></i>
                        Tidak ada data anggota
                    </td></tr>
                <?php else: ?>
                    <?php foreach ($anggotaList as $i => $a): ?>
                        <tr>
                            <td>
                                <div class="member-cell">
                                    <!-- Avatar: foto or initials -->
                                    <div style="position: relative; display: inline-block;">
                                        <?php if (!empty($a['foto']) && file_exists(FOTO_ANGGOTA_DIR . $a['foto'])): ?>
                                            <img src="<?= htmlspecialchars(FOTO_ANGGOTA_URL . $a['foto']) ?>?v=<?= filemtime(FOTO_ANGGOTA_DIR . $a['foto']) ?>"
                                                 style="width: 42px; height: 42px; border-radius: 50%; object-fit: cover; border: 2px solid var(--primary-300, #93c5fd); display: block;" alt="Foto">
                                        <?php else: ?>
                                            <div class="member-avatar avatar-<?= ($a['id'] % 6) + 1 ?>">
                                                <?= strtoupper(substr($a['nama'], 0, 2)) ?>
                                            </div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="member-details">
                                        <div class="member-name"><?= htmlspecialchars($a['nama']) ?></div>
                                        <div class="member-id"><?= htmlspecialchars($a['no_anggota']) ?></div>
                                    </div>
                                </div>
                            </td>
                            <td><?= htmlspecialchars($a['nik'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($a['telepon'] ?? '-') ?></td>
                            <td><?= htmlspecialchars($a['pekerjaan'] ?? '-') ?></td>
                            <td><?= $a['tanggal_daftar'] ? formatTanggal($a['tanggal_daftar']) : '-' ?></td>
                            <td>
                                <span class="badge <?= $a['status'] === 'aktif' ? 'badge-success' : 'badge-danger' ?>">
                                    <?= ucfirst($a['status']) ?>
                                </span>
                            </td>
                            <td>
                                <div class="action-buttons">
                                    <a href="anggota.php?edit=<?= $a['id'] ?>" class="btn btn-icon btn-outline" title="Edit">
                                        <i class="fas fa-pen" style="color: var(--info-500);"></i>
                                    </a>
                                    <form method="POST" style="display:inline;" onsubmit="return confirm('Hapus anggota <?= htmlspecialchars($a['nama'], ENT_QUOTES) ?>?');">
                                        <input type="hidden" name="action" value="delete">
                                        <input type="hidden" name="id" value="<?= $a['id'] ?>">
                                        <button type="submit" class="btn btn-icon btn-outline" title="Hapus">
                                            <i class="fas fa-trash" style="color: var(--danger-500);"></i>
                                        </button>
                                    </form>
                                </div>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php endif; ?>
            </tbody>
        </table>
    </div>

    <?php if ($totalPages > 1): ?>
        <div class="card-footer">
            <div class="pagination">
                <?php if ($page > 1): ?>
                    <a href="anggota.php?page=<?= $page-1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>"><i class="fas fa-chevron-left"></i></a>
                <?php endif; ?>
                <?php for ($p = 1; $p <= $totalPages; $p++): ?>
                    <a href="anggota.php?page=<?= $p ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>" 
                       class="<?= $p === $page ? 'active' : '' ?>"><?= $p ?></a>
                <?php endfor; ?>
                <?php if ($page < $totalPages): ?>
                    <a href="anggota.php?page=<?= $page+1 ?>&search=<?= urlencode($search) ?>&status=<?= urlencode($status) ?>"><i class="fas fa-chevron-right"></i></a>
                <?php endif; ?>
            </div>
        </div>
    <?php endif; ?>
</div>

<!-- Add Modal -->
<div class="modal" id="addModal">
    <div class="modal-header">
        <h3><i class="fas fa-user-plus" style="color: var(--primary-500); margin-right: 8px;"></i>Tambah Anggota Baru</h3>
        <button class="modal-close" onclick="closeModal('addModal')"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="add">
        <div class="modal-body">
            <div class="form-group">
                <label>Nama Lengkap <span class="required">*</span></label>
                <input type="text" name="nama" class="form-control" required placeholder="Masukkan nama lengkap">
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>NIK</label>
                    <input type="text" name="nik" class="form-control" maxlength="16" placeholder="16 digit NIK">
                </div>
                <div class="form-group">
                    <label>Jenis Kelamin</label>
                    <select name="jenis_kelamin" class="form-control">
                        <option value="L">Laki-laki</option>
                        <option value="P">Perempuan</option>
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Tempat Lahir</label>
                    <input type="text" name="tempat_lahir" class="form-control" placeholder="Kota kelahiran">
                </div>
                <div class="form-group">
                    <label>Tanggal Lahir</label>
                    <input type="date" name="tanggal_lahir" class="form-control">
                </div>
            </div>
            <div class="form-group">
                <label>Alamat</label>
                <textarea name="alamat" class="form-control" rows="2" placeholder="Alamat lengkap"></textarea>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Telepon</label>
                    <input type="text" name="telepon" class="form-control" placeholder="08xxxxxxxxxx">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" placeholder="email@contoh.com">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Pekerjaan</label>
                    <input type="text" name="pekerjaan" class="form-control" placeholder="Pekerjaan saat ini">
                </div>
                <div class="form-group">
                    <label>Tanggal Daftar</label>
                    <input type="date" name="tanggal_daftar" class="form-control" value="<?= date('Y-m-d') ?>">
                </div>
            </div>
            <div class="form-group">
                <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                    <input type="checkbox" name="is_konsumsi" value="1" checked style="width: 20px; height: 20px;">
                    <span>Ikut Koperasi Konsumsi</span>
                </label>
                <small class="text-muted">Centang jika anggota ini ikut serta dalam layanan belanja harian (Koperasi Konsumsi).</small>
            </div>
            <div class="form-group" style="margin-top: 15px;">
                <label>Foto Profil</label>
                <input type="file" name="foto" class="form-control" accept="image/*">
                <small class="text-muted">Format: JPG, JPEG, PNG, WebP, GIF. Maks: 5MB</small>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="closeModal('addModal')">Batal</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Simpan</button>
        </div>
    </form>
</div>

<!-- Edit Modal -->
<?php if ($editData): ?>
<script>document.addEventListener('DOMContentLoaded', () => openModal('editModal'));</script>
<div class="modal" id="editModal">
    <div class="modal-header">
        <h3><i class="fas fa-user-edit" style="color: var(--info-500); margin-right: 8px;"></i>Edit Anggota</h3>
        <button class="modal-close" onclick="window.location='anggota.php'"><i class="fas fa-times"></i></button>
    </div>
    <form method="POST" enctype="multipart/form-data">
        <input type="hidden" name="action" value="edit">
        <input type="hidden" name="id" value="<?= $editData['id'] ?>">
        <input type="hidden" name="old_foto" value="<?= $editData['foto'] ?>">
        <div class="modal-body">
            <div class="form-group">
                <label>No Anggota</label>
                <input type="text" class="form-control" value="<?= htmlspecialchars($editData['no_anggota']) ?>" disabled>
            </div>
            <div class="form-group">
                <label>Nama Lengkap <span class="required">*</span></label>
                <input type="text" name="nama" class="form-control" required value="<?= htmlspecialchars($editData['nama']) ?>">
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>NIK</label>
                    <input type="text" name="nik" class="form-control" maxlength="16" value="<?= htmlspecialchars($editData['nik'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Jenis Kelamin</label>
                    <select name="jenis_kelamin" class="form-control">
                        <option value="L" <?= $editData['jenis_kelamin'] === 'L' ? 'selected' : '' ?>>Laki-laki</option>
                        <option value="P" <?= $editData['jenis_kelamin'] === 'P' ? 'selected' : '' ?>>Perempuan</option>
                    </select>
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Tempat Lahir</label>
                    <input type="text" name="tempat_lahir" class="form-control" value="<?= htmlspecialchars($editData['tempat_lahir'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Tanggal Lahir</label>
                    <input type="date" name="tanggal_lahir" class="form-control" value="<?= $editData['tanggal_lahir'] ?? '' ?>">
                </div>
            </div>
            <div class="form-group">
                <label>Alamat</label>
                <textarea name="alamat" class="form-control" rows="2"><?= htmlspecialchars($editData['alamat'] ?? '') ?></textarea>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Telepon</label>
                    <input type="text" name="telepon" class="form-control" value="<?= htmlspecialchars($editData['telepon'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Email</label>
                    <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($editData['email'] ?? '') ?>">
                </div>
            </div>
            <div class="form-row">
                <div class="form-group">
                    <label>Pekerjaan</label>
                    <input type="text" name="pekerjaan" class="form-control" value="<?= htmlspecialchars($editData['pekerjaan'] ?? '') ?>">
                </div>
                <div class="form-group">
                    <label>Status</label>
                    <select name="status" class="form-control">
                        <option value="aktif" <?= $editData['status'] === 'aktif' ? 'selected' : '' ?>>Aktif</option>
                        <option value="nonaktif" <?= $editData['status'] === 'nonaktif' ? 'selected' : '' ?>>Nonaktif</option>
                    </select>
                </div>
            </div>
            <div class="form-group">
                <label style="display: flex; align-items: center; gap: 8px; cursor: pointer;">
                    <input type="checkbox" name="is_konsumsi" value="1" <?= $editData['is_konsumsi'] ? 'checked' : '' ?> style="width: 20px; height: 20px;">
                    <span>Ikut Koperasi Konsumsi</span>
                </label>
                <small class="text-muted">Centang jika anggota ini ikut serta dalam layanan belanja harian (Koperasi Konsumsi).</small>
            </div>
            <div class="form-group" style="margin-top: 15px;">
                <label>Foto Profil (Biarkan kosong jika tidak diubah)</label>
                <input type="file" name="foto" class="form-control" accept="image/*">
                <small class="text-muted">Format: JPG, JPEG, PNG, WebP, GIF. Maks: 5MB</small>
            </div>
            <?php if (!empty($editData['foto']) && file_exists(FOTO_ANGGOTA_DIR . $editData['foto'])): ?>
                <div style="margin-top: 10px; margin-bottom: 15px;">
                    <label>Foto Saat Ini:</label><br>
                    <img src="<?= htmlspecialchars(FOTO_ANGGOTA_URL . $editData['foto']) ?>" style="width: 80px; height: 80px; object-fit: cover; border-radius: 8px; border: 1px solid var(--gray-200);">
                </div>
            <?php endif; ?>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-outline" onclick="window.location='anggota.php'">Batal</button>
            <button type="submit" class="btn btn-primary"><i class="fas fa-save"></i> Perbarui</button>
        </div>
    </form>
</div>
<?php endif; ?>

<?php include __DIR__ . '/includes/footer.php'; ?>
