<?php
/**
 * admin/update-member.php
 * Update an existing member.
 */

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();

header('Content-Type: application/json');

try {
    $id            = (int)($_POST['id'] ?? 0);
    $membership_id = trim($_POST['membership_id'] ?? '');
    $full_name     = trim($_POST['full_name'] ?? '');
    $gender        = trim($_POST['gender'] ?? '');
    $phone         = trim($_POST['phone'] ?? '');
    $kindred       = trim($_POST['kindred'] ?? '');

    if ($id <= 0 || empty($membership_id) || empty($full_name) || empty($gender) || empty($phone)) {
        throw new Exception('All fields except Kindred are required.');
    }

    // Check duplicate membership_id except for this record
    $stmt = $pdo->prepare("SELECT id FROM members WHERE membership_id = ? AND id != ?");
    $stmt->execute([$membership_id, $id]);
    if ($stmt->fetch()) {
        throw new Exception('Membership ID already used by another member.');
    }

    $sql = "UPDATE members
            SET membership_id = ?, full_name = ?, gender = ?, phone = ?, kindred = ?
            WHERE id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$membership_id, $full_name, $gender, $phone, $kindred, $id]);

    echo json_encode(['success' => true, 'message' => 'Member updated successfully.']);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}