<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
include '../connection.php';

if(isset($_POST['user_id']) && isset($_POST['phone'])) {
    $user_id = intval($_POST['user_id']);
    $phone = $_POST['phone'];

    // Check if profile already exists
    $checkQuery = "SELECT id FROM tbl_profile WHERE user_id = ?";
    $stmt = $conn->prepare($checkQuery);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if($result->num_rows > 0){
        // Update existing
        $updateQuery = "UPDATE tbl_profile SET phone = ? WHERE user_id = ?";
        $stmt2 = $conn->prepare($updateQuery);
        $stmt2->bind_param("si", $phone, $user_id);
        $stmt2->execute();
    } else {
        // Insert new
        /*
        $insertQuery = "INSERT INTO tbl_profile (user_id, phone) VALUES (?, ?)";
        $stmt2 = $conn->prepare($insertQuery);
        $stmt2->bind_param("is", $user_id, $phone);
        $stmt2->execute();
        */
        echo json_encode([
            "success" => false,
            "message" => "Please update your profile first, then place order, thanks.."
        ]);
    }

    echo json_encode([
        "success" => true,
        "message" => "Phone number saved successfully"
    ]);

} else {
    echo json_encode([
        "success" => false,
        "message" => "Missing parameters"
    ]);
}
?>
