<?php
header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

require_once "config.php"; // ✅ DB connection

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $input = json_decode(file_get_contents("php://input"), true);

    if (!$input) {
        echo json_encode(["status" => "error", "message" => "Invalid JSON input"]);
        exit;
    }

    // --- Extract all fields safely ---
    $fields = [
        "first_name","last_name","country","phone","dob","email","password",
        "uid","email_confirmed","number","number_confirmed","two_factor_enabled",
        "lockout_end_date","lockout_enabled","access_count_failed","username",
        "fullname","byPartner","date","status","dial_code","Isreferal","referalId",
        "zipcode","address","aboutme","imgName","education","industry","financial_industry",
        "forex_exp","monthly_transaction","investment_plan","funds_source","investment_purpose",
        "total_value","annual_income","polotically_person","bankruptcy","usa_resident","usa_tax",
        "emailToken","state","city","lang","email_token_time","profile_image","gender","referral",
        "mail_otp","employee_status","cfd","other","kyc_type","kyc_front","kyc_back","bank_detail",
        "account_holder_name","bank_name","bank_account_no","IFSC_Code","swift_code","kyc_verify",
        "client_status","wallet_address","bank_status","personal_status","employemnet_status","trading_status",
        "parent_id","ib1","ib2","ib3","ib4","ib5","ib6","ib7","ib8","ib9","ib10",
        "ib11","ib12","ib13","ib14","ib15","ib16","ib17","ib18","ib19","ib20",
        "level","account","iv"
    ];

    $data = [];
    foreach ($fields as $f) {
        $data[$f] = $conn->real_escape_string($input[$f] ?? "");
    }

    $id = $conn->real_escape_string($input['id'] ?? "");

    // --- Validation ---
    if (empty($data['email']) || empty($data['phone']) || empty($data['country'])) {
        echo json_encode(["status" => "error", "message" => "Required fields missing (email, phone, country)"]);
        exit;
    }

    if (!empty($id)) {
        // ✅ Update record if exists
        $check = $conn->query("SELECT id FROM loginusers WHERE id='$id'");
        if ($check && $check->num_rows > 0) {
            $updateSet = [];
            foreach ($data as $col => $val) {
                $updateSet[] = "$col='$val'";
            }
            $sql = "UPDATE loginusers SET " . implode(",", $updateSet) . " WHERE id='$id'";
            $msg = "Profile updated successfully";
        } else {
            echo json_encode(["status" => "error", "message" => "User with given ID not found"]);
            exit;
        }
    } else {
        // ✅ Insert new record
        $columns = implode(",", array_keys($data));
        $values  = "'" . implode("','", array_values($data)) . "'";
        $sql = "INSERT INTO loginusers ($columns) VALUES ($values)";
        $msg = "Profile created successfully";
    }

    if ($conn->query($sql)) {
        echo json_encode(["status" => "success", "message" => $msg]);
    } else {
        echo json_encode(["status" => "error", "message" => "DB Error: " . $conn->error]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "Only POST method allowed"]);
}
