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

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

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception("Only POST method allowed");
    }

    $input = json_decode(file_get_contents("php://input"), true);
    if (!$input) {
        throw new Exception("Invalid JSON input");
    }

    // --- Get all columns from table ---
    $existingColumns = [];
    $result = $conn->query("SHOW COLUMNS FROM loginusers");
    while ($row = $result->fetch_assoc()) {
        $existingColumns[] = $row['Field'];
    }

    // --- Filter input data to only include existing columns ---
    $data = [];
    foreach ($input as $key => $val) {
        if (in_array($key, $existingColumns)) {
            $data[$key] = $val;
        }
    }

    $id = $data['id'] ?? null;
    unset($data['id']); // Remove ID from data array for insert/update

    // --- Validation ---
    if (empty($data['email']) || empty($data['phone']) || empty($data['country'])) {
        throw new Exception("Required fields missing (email, phone, country)");
    }

    if ($id) {
        // ✅ UPDATE existing user
        $check = $conn->prepare("SELECT id FROM loginusers WHERE id = ?");
        $check->bind_param("i", $id);
        $check->execute();
        $check->store_result();
        if ($check->num_rows === 0) {
            throw new Exception("User with given ID not found");
        }
        $check->close();

        // Build dynamic UPDATE query
        $setParts = [];
        $types = "";
        $values = [];
        foreach ($data as $col => $val) {
            $setParts[] = "$col = ?";
            $types .= "s";
            $values[] = $val;
        }
        $types .= "i"; // For WHERE id
        $values[] = $id;

        $sql = "UPDATE loginusers SET " . implode(",", $setParts) . " WHERE id = ?";
        $stmt = $conn->prepare($sql);
        if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);

        $stmt->bind_param($types, ...$values);
        $stmt->execute();
        $stmt->close();

        echo json_encode(["status" => "success", "message" => "Profile updated successfully"]);

    } else {
        // ✅ INSERT new user
        $columns = implode(",", array_keys($data));
        $placeholders = implode(",", array_fill(0, count($data), "?"));
        $types = str_repeat("s", count($data));
        $values = array_values($data);

        $stmt = $conn->prepare("INSERT INTO loginusers ($columns) VALUES ($placeholders)");
        if (!$stmt) throw new Exception("Prepare failed: " . $conn->error);

        $stmt->bind_param($types, ...$values);
        $stmt->execute();
        $stmt->close();

        echo json_encode(["status" => "success", "message" => "Profile created successfully"]);
    }

} catch (Exception $e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}

$conn->close();
?>
