<?php
/**
 * admin/save-member.php
 * Save a new 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 {
    $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 (empty($membership_id) || empty($full_name) || empty($gender) || empty($phone)) {
        throw new Exception('All fields except Kindred are required.');
    }

    // Check duplicate membership_id
    $stmt = $pdo->prepare("SELECT id FROM members WHERE membership_id = ?");
    $stmt->execute([$membership_id]);
    if ($stmt->fetch()) {
        throw new Exception('Membership ID already exists. Please use a unique one.');
    }

    // Insert (email is not provided, set NULL; date_joined = NOW(); created_at = NOW())
    $sql = "INSERT INTO members (membership_id, full_name, gender, phone, email, kindred, date_joined, created_at)
            VALUES (?, ?, ?, ?, NULL, ?, NOW(), NOW())";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$membership_id, $full_name, $gender, $phone, $kindred]);

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