<?php
session_start();
include_once 'config.php';
include_once 'function.php';

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

if (!isset($_SESSION['login'])) {
    echo json_encode(['status' => 'error', 'message' => 'Unauthorized']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $active_event_id = get_active_event_id();
    if (!$active_event_id) {
        echo json_encode(['status' => 'error', 'message' => 'No active event']);
        exit;
    }

    $inputJSON = file_get_contents('php://input');
    $input = json_decode($inputJSON, true);

    if (isset($input['contacts']) && is_array($input['contacts'])) {
        $added = 0;
        $tgl = date('d-m-Y');
        $jam = date('H:i');
        
        foreach ($input['contacts'] as $contact) {
            $nama = isset($contact['name']) ? $contact['name'] : '';
            $whatsapp = isset($contact['tel']) ? $contact['tel'] : '';
            $tamu = 'Umum'; // Default category

            // Clean whatsapp number
            $whatsapp = preg_replace('/[^0-9]/', '', $whatsapp);
            if(substr($whatsapp, 0, 1) === '0') $whatsapp = '62' . substr($whatsapp, 1);
            else if(substr($whatsapp, 0, 1) === '8') $whatsapp = '628' . substr($whatsapp, 1);

            if (!empty($nama)) {
                $nama = mysqli_real_escape_string($koneksi, htmlspecialchars($nama));
                $whatsapp = mysqli_real_escape_string($koneksi, htmlspecialchars($whatsapp));
                $koneksi->query("INSERT INTO comment_id (nama, tgl, jam, whatsapp, tamu, event_id) VALUES ('".$nama."', '".$tgl."', '".$jam."', '".$whatsapp."','".$tamu."', '".$active_event_id."')");
                $added++;
            }
        }
        echo json_encode(['status' => 'success', 'added' => $added]);
    } else {
        echo json_encode(['status' => 'error', 'message' => 'No contacts received']);
    }
}
?>
