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

// === KREDENSIAL DB (GANTI SESUAI SERVER) ===
$servername = "localhost";
$username   = "mdcc5937_mdc";
$password   = "mdcc5937_mdc"; // kosongkan jika tak perlu
$dbname     = "mdcc5937_mdc";

// Ambil JSON
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

// Validasi minimal: wajib ada WA
if (empty($data) || !isset($data['wa']) || trim($data['wa']) === '') {
    http_response_code(400);
    echo json_encode(['ok' => false, 'error' => 'Data tidak valid. WA tidak boleh kosong.']);
    exit;
}

// Sanitasi ringan
$nama   = htmlspecialchars($data['nama']   ?? '', ENT_QUOTES, 'UTF-8');
$wa     = htmlspecialchars(trim($data['wa']), ENT_QUOTES, 'UTF-8');
$gender = htmlspecialchars($data['gender'] ?? '', ENT_QUOTES, 'UTF-8');
$gereja = htmlspecialchars($data['gereja'] ?? '', ENT_QUOTES, 'UTF-8');
$alamat = htmlspecialchars($data['alamat'] ?? '', ENT_QUOTES, 'UTF-8');

// Koneksi
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    http_response_code(500);
    echo json_encode(['ok' => false, 'error' => 'Koneksi database gagal: ' . $conn->connect_error]);
    exit;
}

// (Opsional aman): pastikan tabel ada — hapus bagian ini jika tabel sudah disiapkan manual
$conn->query("
CREATE TABLE IF NOT EXISTS kehadiran (
  id INT UNSIGNED NOT NULL AUTO_INCREMENT,
  nama   VARCHAR(255) NOT NULL,
  wa     VARCHAR(20)  NOT NULL,
  gender VARCHAR(20)  NOT NULL,
  gereja VARCHAR(100) NOT NULL,
  alamat TEXT         NOT NULL,
  scan_time TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (id),
  UNIQUE KEY uniq_wa (wa),
  KEY idx_scan_time (scan_time)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
");

// Cek apakah WA sudah ada
$stmt_check = $conn->prepare("SELECT id FROM kehadiran WHERE wa = ?");
$stmt_check->bind_param("s", $wa);
$stmt_check->execute();
$result_check = $stmt_check->get_result();

$response = ['ok' => false, 'count' => 0];

if ($result_check && $result_check->num_rows > 0) {
    // Sudah ada -> HANYA update scan_time
    $stmt_update = $conn->prepare("UPDATE kehadiran SET scan_time = CURRENT_TIMESTAMP() WHERE wa = ?");
    $stmt_update->bind_param("s", $wa);
    if ($stmt_update->execute()) {
        $response['ok'] = true;
    } else {
        http_response_code(500);
        $response['error'] = 'Gagal memperbarui data: ' . $stmt_update->error;
    }
    $stmt_update->close();
} else {
    // Belum ada -> simpan data lengkap
    $stmt_insert = $conn->prepare("INSERT INTO kehadiran (nama, wa, gender, gereja, alamat) VALUES (?, ?, ?, ?, ?)");
    $stmt_insert->bind_param("sssss", $nama, $wa, $gender, $gereja, $alamat);
    if ($stmt_insert->execute()) {
        $response['ok'] = true;
    } else {
        http_response_code(500);
        $response['error'] = 'Gagal menyimpan data baru: ' . $stmt_insert->error;
    }
    $stmt_insert->close();
}
$stmt_check->close();

// Hitung total hadir
$count_result = $conn->query("SELECT COUNT(*) AS total FROM kehadiran");
if ($count_result) {
    $count_row = $count_result->fetch_assoc();
    $response['count'] = (int)$count_row['total'];
}

$conn->close();
echo json_encode($response);