<?php
include 'includes/db.php'; // adjust as needed

$csv = fopen('Gym Client Data neil 2(Sheet1).csv', 'r');
fgetcsv($csv); // skip header

while (($row = fgetcsv($csv)) !== false) {
    $first = trim($row[0]);
    $surname = trim($row[1]);
    $email = trim($row[2]);
    $phone = trim($row[3]);
    $membership = trim($row[4]);
    $expiry = trim($row[5]);

    if ($first === '' && $surname === '') continue;

    // Check if member exists by name
    $check = $conn->prepare("SELECT id FROM members WHERE first_name = ? AND surname = ?");
    $check->bind_param('ss', $first, $surname);
    $check->execute();
    $check->store_result();

    if ($check->num_rows > 0) {
        // Update existing
        $update = $conn->prepare("UPDATE members SET email = ?, phone = ?, membership_type = ?, expiry_date = ? WHERE first_name = ? AND surname = ?");
        $update->bind_param('ssssss', $email, $phone, $membership, $expiry, $first, $surname);
        $update->execute();
    } else {
        // Only insert if email is not blank OR does not already exist
        if (!empty($email)) {
            // Ensure no duplicate email
            $emailCheck = $conn->prepare("SELECT id FROM members WHERE email = ?");
            $emailCheck->bind_param('s', $email);
            $emailCheck->execute();
            $emailCheck->store_result();

            if ($emailCheck->num_rows === 0) {
                $insert = $conn->prepare("INSERT INTO members (first_name, surname, email, phone, membership_type, expiry_date, payment_status) VALUES (?, ?, ?, ?, ?, ?, 'OK')");
                $insert->bind_param('ssssss', $first, $surname, $email, $phone, $membership, $expiry);
                $insert->execute();
            }
        }
    }
}
fclose($csv);

echo "Import complete.";
?>
