<?php
include('db_con.php');

$apiDataEncoded = file_get_contents('php://input');
$apiData = json_decode($apiDataEncoded);
$uname = $apiData->data->object->custom_fields[0]->text->value;
$uemail = $apiData->data->object->customer_details->email;
$customerId = $apiData->data->object->customer;

$sql = $db_con->prepare('SELECT id FROM users WHERE uname = :uname');
$sql->bindValue(':uname', $uname);
$sql->execute();
$numRows = $sql->rowCount();

if($numRows > 0){
    $userData = $sql->fetch(PDO::FETCH_ASSOC);
    $user_id = $userData['id'];
    
    $stmt = $db_con->prepare("UPDATE users SET stripe_cu = :customerId WHERE id = :id");
    $stmt->bindValue(':customerId', $customerId);
    $stmt->bindValue(':id', $user_id);
    $stmt->execute();
}else{
    $sql = $db_con->prepare('SELECT id FROM users WHERE u_email = :u_email');
    $sql->bindValue(':u_email', $uemail);
    $sql->execute();
    $numRows = $sql->rowCount();
    
    if($numRows > 0){
        $userData = $sql->fetch(PDO::FETCH_ASSOC);
        $user_id = $userData['id'];
        
        $stmt = $db_con->prepare("UPDATE users SET stripe_cu = :customerId WHERE id = :id");
        $stmt->bindValue(':customerId', $customerId);
        $stmt->bindValue(':id', $user_id);
        $stmt->execute();
    }else{
        die('Incorrect details');
    }
}
die();
?>