<?php
session_start();
include "../../connect/db.php";
csrf_verify();

if (!isset($_SESSION['chap'])) {
    exit("not logged in");
}

$email = $con->real_escape_string($_SESSION['chap']);

// Collect fields
$fields = [
    "zipcode","address","state","ssn","city","occupation","income",
    "next_kin","next_address","next_relationship",
    "securityquestion","answer","securityquestion2","answer2","pincode"
];

$setParts = [];
foreach ($fields as $f) {
    if (isset($_POST[$f])) {
        $val = trim($_POST[$f]);

        // ✅ Validate pincode: must be exactly 4 digits
        if ($f === "pincode") {
            if (!preg_match("/^[0-9]{4}$/", $val)) {
                exit("Error: Pincode must be exactly 4 digits (numbers only).");
            }
        }

        $val = $con->real_escape_string($val);
        $setParts[] = "`$f` = '$val'";
    }
}

// Always set KYC status
$setParts[] = "kyc_status = 'review'";

$sql = "UPDATE users SET " . implode(", ", $setParts) . " WHERE email = '$email'";

if ($con->query($sql)) {
    echo "KYC submitted successfully. Status: Review";
} else {
    echo "Error: " . $con->error;
}
?>
