<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Include required files
include('../koneksi.php');
require '../kalenderhijriah.php';

// Function to convert phone number format
function convertnohp($phoneNumber) {
    // Remove non-numeric characters
    $phoneNumber = preg_replace('/[^0-9]/', '', $phoneNumber);
    
    // Check if number starts with 0
    if (substr($phoneNumber, 0, 1) == '0') {
        // Replace leading 0 with 62
        $phoneNumber = '62' . substr($phoneNumber, 1);
    } 
    // Check if number doesn't start with 62
    elseif (substr($phoneNumber, 0, 2) != '62') {
        // Add 62 prefix
        $phoneNumber = '62' . $phoneNumber;
    }
    
    return $phoneNumber;
}

// Start session if not already started
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// Get username from session
$kode = isset($_SESSION['username']) ? $_SESSION['username'] : '';

// Get form data from POST
$r_register = isset($_POST['r_register']) ? $_POST['r_register'] : '';
$r_tgl = isset($_POST['r_tgl']) ? $_POST['r_tgl'] : '';
$r_nik = isset($_POST['r_nik']) ? $_POST['r_nik'] : '';
$r_nama = isset($_POST['r_nama']) ? $_POST['r_nama'] : '';
$r_kelamin = isset($_POST['r_kelamin']) ? $_POST['r_kelamin'] : '';
$r_ttl = isset($_POST['r_ttl']) ? $_POST['r_ttl'] : '';
$r_tgll = isset($_POST['r_tgll']) ? $_POST['r_tgll'] : '';
$r_alamat = isset($_POST['r_alamat']) ? $_POST['r_alamat'] : '';
$r_rtrw = isset($_POST['r_rtrw']) ? $_POST['r_rtrw'] : '';
$r_desa = isset($_POST['r_desa']) ? $_POST['r_desa'] : '';
$r_kecamatan = isset($_POST['r_kecamatan']) ? $_POST['r_kecamatan'] : '';
$r_kabupaten = isset($_POST['r_kabupaten']) ? $_POST['r_kabupaten'] : '';
$r_ibu = isset($_POST['r_ibu']) ? $_POST['r_ibu'] : '';
$r_pekerjaan = isset($_POST['r_pekerjaan']) ? $_POST['r_pekerjaan'] : '';
$r_nohp = isset($_POST['r_nohp']) ? convertnohp($_POST['r_nohp']) : '';
$kelas = isset($_POST['r_kelas']) ? $_POST['r_kelas'] : '';

// Format dates properly
try {
    // Convert r_tgl from DD-MM-YYYY to YYYY-MM-DD for database
    if (!empty($r_tgl)) {
        // Check if the date format is DD-MM-YYYY
        if (preg_match('/^\d{1,2}-\d{1,2}-\d{4}$/', $r_tgl)) {
            $date_parts = explode('-', $r_tgl);
            if (count($date_parts) === 3) {
                $r_tgl = $date_parts[2] . '-' . $date_parts[1] . '-' . $date_parts[0];
            }
        }
    }

    // Ensure r_tgll is in the correct format
    if (!empty($r_tgll)) {
        $r_tgll = date('Y-m-d', strtotime($r_tgll));
    }
} catch (Exception $e) {
    echo "Date conversion error: " . $e->getMessage();
    exit;
}

// Validate required data
if (empty($r_register)) {
    echo "Error: Register ID is required";
    exit;
}

// Prepare data for update (prevent SQL injection)
$r_register = mysqli_real_escape_string($koneksi, $r_register);
$r_tgl = mysqli_real_escape_string($koneksi, $r_tgl);
$r_nik = mysqli_real_escape_string($koneksi, $r_nik);
$r_nama = mysqli_real_escape_string($koneksi, $r_nama);
$r_kelamin = mysqli_real_escape_string($koneksi, $r_kelamin);
$r_ttl = mysqli_real_escape_string($koneksi, $r_ttl);
$r_tgll = mysqli_real_escape_string($koneksi, $r_tgll);
$r_alamat = mysqli_real_escape_string($koneksi, $r_alamat);
$r_rtrw = mysqli_real_escape_string($koneksi, $r_rtrw);
$r_desa = mysqli_real_escape_string($koneksi, $r_desa);
$r_kecamatan = mysqli_real_escape_string($koneksi, $r_kecamatan);
$r_kabupaten = mysqli_real_escape_string($koneksi, $r_kabupaten);
$r_ibu = mysqli_real_escape_string($koneksi, $r_ibu);
$r_pekerjaan = mysqli_real_escape_string($koneksi, $r_pekerjaan);
$r_nohp = mysqli_real_escape_string($koneksi, $r_nohp);
$kelas = mysqli_real_escape_string($koneksi, $kelas);

// Construct SQL query for update
$query = "UPDATE registrasi SET 
            nik='$r_nik',
            tgl='$r_tgl',
            nama='$r_nama',
            kelamin='$r_kelamin',
            ttl='$r_ttl',
            tgll='$r_tgll',
            alamat='$r_alamat',
            rtrw='$r_rtrw',
            desa='$r_desa',
            kec='$r_kecamatan',
            kab='$r_kabupaten',
            ibu='$r_ibu',
            wali='$r_pekerjaan',
            nohp='$r_nohp',
            klsNow='$kelas',
            username='$kode'
          WHERE id='$r_register'";

// Execute query
if (mysqli_query($koneksi, $query)) {
    echo "Data Sukses Disimpan!";
} else {
    echo "Error updating record: " . mysqli_error($koneksi);
}

// Close connection
mysqli_close($koneksi);
?>